Run python scripts in windows

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Running Python Scripts

One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. This is going to be the only way for you to know if your code works as you planned. It’s even the only way of knowing if your code works at all!

This step-by-step tutorial will guide you through a series of ways to run Python scripts, depending on your environment, platform, needs, and skills as a programmer.

You’ll have the opportunity to learn how to run Python scripts by using:

  • The operating system command-line or terminal
  • The Python interactive mode
  • The IDE or text editor you like best
  • The file manager of your system, by double-clicking on the icon of your script

This way, you’ll get the knowledge and skills you’ll need to make your development cycle more productive and flexible.

Scripts vs Modules

In computing, the word script is used to refer to a file containing a logical sequence of orders or a batch processing file. This is usually a simple program, stored in a plain text file.

Scripts are always processed by some kind of interpreter, which is responsible for executing each command sequentially.

A plain text file containing Python code that is intended to be directly executed by the user is usually called script, which is an informal term that means top-level program file.

On the other hand, a plain text file, which contains Python code that is designed to be imported and used from another Python file, is called module.

So, the main difference between a module and a script is that modules are meant to be imported, while scripts are made to be directly executed.

In either case, the important thing is to know how to run the Python code you write into your modules and scripts.

What’s the Python Interpreter?

Python is an excellent programming language that allows you to be productive in a wide variety of fields.

Python is also a piece of software called an interpreter. The interpreter is the program you’ll need to run Python code and scripts. Technically, the interpreter is a layer of software that works between your program and your computer hardware to get your code running.

Depending on the Python implementation you use, the interpreter can be:

  • A program written in C, like CPython, which is the core implementation of the language
  • A program written in Java, like Jython
  • A program written in Python itself, like PyPy
  • A program implemented in .NET, like IronPython

Whatever form the interpreter takes, the code you write will always be run by this program. Therefore, the first condition to be able to run Python scripts is to have the interpreter correctly installed on your system.

The interpreter is able to run Python code in two different ways:

  • As a script or module
  • As a piece of code typed into an interactive session

How to Run Python Code Interactively

A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python, or python3 depending on your Python installation, and then hit Enter.

Here’s an example of how to do this on Linux:

$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

The standard prompt for the interactive mode is >>>, so as soon as you see these characters, you’ll know you are in.

Now, you can write and run Python code as you wish, with the only drawback being that when you close the session, your code will be gone.

When you work interactively, every expression and statement you type in is evaluated and executed immediately:

>>>

>>> print('Hello World!')
Hello World!
>>> 2 + 5
7
>>> print('Welcome to Real Python!')
Welcome to Real Python!

An interactive session will allow you to test every piece of code you write, which makes it an awesome development tool and an excellent place to experiment with the language and test Python code on the fly.

To exit interactive mode, you can use one of the following options:

  • quit() or exit(), which are built-in functions
  • The Ctrl+Z and Enter key combination on Windows, or just Ctrl+D on Unix-like systems

If you’ve never worked with the command-line or terminal, then you can try this:

  • On Windows, the command-line is usually known as command prompt or MS-DOS console, and it is a program called cmd.exe. The path to this program can vary significantly from one system version to another.

    A quick way to get access to it is by pressing the Win+R key combination, which will take you to the Run dialog. Once you’re there, type in cmd and press Enter.

  • On GNU/Linux (and other Unixes), there are several applications that give you access to the system command-line. Some of the most popular are xterm, Gnome Terminal, and Konsole. These are tools that run a shell or terminal like Bash, ksh, csh, and so on.

    In this case, the path to these applications is much more varied and depends on the distribution and even on the desktop environment you use. So, you’ll need to read your system documentation.

  • On Mac OS X, you can access the system terminal from Applications → Utilities → Terminal.

How Does the Interpreter Run Python Scripts?

When you try to run Python scripts, a multi-step process begins. In this process the interpreter will:

  1. Process the statements of your script in a sequential fashion

  2. Compile the source code to an intermediate format known as bytecode

    This bytecode is a translation of the code into a lower-level language that’s platform-independent. Its purpose is to optimize code execution. So, the next time the interpreter runs your code, it’ll bypass this compilation step.

    Strictly speaking, this code optimization is only for modules (imported files), not for executable scripts.

  3. Ship off the code for execution

    At this point, something known as a Python Virtual Machine (PVM) comes into action. The PVM is the runtime engine of Python. It is a cycle that iterates over the instructions of your bytecode to run them one by one.

    The PVM is not an isolated component of Python. It’s just part of the Python system you’ve installed on your machine. Technically, the PVM is the last step of what is called the Python interpreter.

The whole process to run Python scripts is known as the Python Execution Model.

How to Run Python Scripts Using the Command-Line

A Python interactive session will allow you to write a lot of lines of code, but once you close the session, you lose everything you’ve written. That’s why the usual way of writing Python programs is by using plain text files. By convention, those files will use the .py extension. (On Windows systems the extension can also be .pyw.)

Python code files can be created with any plain text editor. If you are new to Python programming, you can try Sublime Text, which is a powerful and easy-to-use editor, but you can use any editor you like.

To keep moving forward in this tutorial, you’ll need to create a test script. Open your favorite text editor and write the following code:

 1#!/usr/bin/env python3
 2
 3print('Hello World!')

Save the file in your working directory with the name hello.py. With the test script ready, you can continue reading.

Using the python Command

To run Python scripts with the python command, you need to open a command-line and type in the word python, or python3 if you have both versions, followed by the path to your script, just like this:

$ python3 hello.py
Hello World!

If everything works okay, after you press Enter, you’ll see the phrase Hello World! on your screen. That’s it! You’ve just run your first Python script!

If this doesn’t work right, maybe you’ll need to check your system PATH, your Python installation, the way you created the hello.py script, the place where you saved it, and so on.

This is the most basic and practical way to run Python scripts.

Redirecting the Output

Sometimes it’s useful to save the output of a script for later analysis. Here’s how you can do that:

$ python3 hello.py > output.txt

This operation redirects the output of your script to output.txt, rather than to the standard system output (stdout). The process is commonly known as stream redirection and is available on both Windows and Unix-like systems.

If output.txt doesn’t exist, then it’s automatically created. On the other hand, if the file already exists, then its contents will be replaced with the new output.

Finally, if you want to add the output of consecutive executions to the end of output.txt, then you must use two angle brackets (>>) instead of one, just like this:

$ python3 hello.py >> output.txt

Now, the output will be appended to the end of output.txt.

Running Modules With the -m Option

Python offers a series of command-line options that you can use according to your needs. For example, if you want to run a Python module, you can use the command python -m <module-name>.

The -m option searches sys.path for the module name and runs its content as __main__:

$ python3 -m hello
Hello World!

Using the Script Filename

On recent versions of Windows, it is possible to run Python scripts by simply entering the name of the file containing the code at the command prompt:

C:\devspace> hello.py
Hello World!

This is possible because Windows uses the system registry and the file association to determine which program to use for running a particular file.

On Unix-like systems, such as GNU/Linux, you can achieve something similar. You’ll only have to add a first line with the text #!/usr/bin/env python, just as you did with hello.py.

For Python, this is a simple comment, but for the operating system, this line indicates what program must be used to run the file.

This line begins with the #! character combination, which is commonly called hash bang or shebang, and continues with the path to the interpreter.

There are two ways to specify the path to the interpreter:

  • #!/usr/bin/python: writing the absolute path
  • #!/usr/bin/env python: using the operating system env command, which locates and executes Python by searching the PATH environment variable

This last option is useful if you bear in mind that not all Unix-like systems locate the interpreter in the same place.

Finally, to execute a script like this one, you need to assign execution permissions to it and then type in the filename at the command-line.

Here’s an example of how to do this:

$ # Assign execution permissions
$ chmod +x hello.py
$ # Run the script by using its filename
$ ./hello.py
Hello World!

With execution permissions and the shebang line properly configured, you can run the script by simply typing its filename at the command-line.

Finally, you need to note that if your script isn’t located at your current working directory, you’ll have to use the file path for this method to work correctly.

How to Run Python Scripts Interactively

It is also possible to run Python scripts and modules from an interactive session. This option offers you a variety of possibilities.

Taking Advantage of import

When you import a module, what really happens is that you load its contents for later access and use. The interesting thing about this process is that import runs the code as its final step.

When the module contains only classes, functions, variables, and constants definitions, you probably won’t be aware that the code was actually run, but when the module includes calls to functions, methods, or other statements that generate visible results, then you’ll witness its execution.

This provides you with another option to run Python scripts:

>>>

>>> import hello
Hello World!

You’ll have to note that this option works only once per session. After the first import, successive import executions do nothing, even if you modify the content of the module. This is because import operations are expensive and therefore run only once. Here’s an example:

>>>

>>> import hello  # Do nothing
>>> import hello  # Do nothing again

These two import operations do nothing, because Python knows that hello has already been imported.

There are some requirements for this method to work:

  • The file with the Python code must be located in your current working directory.
  • The file must be in the Python Module Search Path (PMSP), where Python looks for the modules and packages you import.

To know what’s in your current PMSP, you can run the following code:

>>>

>>> import sys
>>> for path in sys.path:
...     print(path)
...
/usr/lib/python36.zip
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages

Running this code, you’ll get the list of directories and .zip files where Python searches the modules you import.

Using importlib and imp

In the Python Standard Library, you can find importlib, which is a module that provides import_module().

With import_module(), you can emulate an import operation and, therefore, execute any module or script. Take a look at this example:

>>>

>>> import importlib
>>> importlib.import_module('hello')
Hello World!
<module 'hello' from '/home/username/hello.py'>

Once you’ve imported a module for the first time, you won’t be able to continue using import to run it. In this case, you can use importlib.reload(), which will force the interpreter to re-import the module again, just like in the following code:

>>>

>>> import hello  # First import
Hello World!
>>> import hello  # Second import, which does nothing
>>> import importlib
>>> importlib.reload(hello)
Hello World!
<module 'hello' from '/home/username/hello.py'>

An important point to note here is that the argument of reload() has to be the name of a module object, not a string:

>>>

>>> importlib.reload('hello')
Traceback (most recent call last):
    ...
TypeError: reload() argument must be a module

If you use a string as an argument, then reload() will raise a TypeError exception.

importlib.reload() comes in handy when you are modifying a module and want to test if your changes work, without leaving the current interactive session.

Finally, if you are using Python 2.x, then you’ll have imp, which is a module that provides a function called reload(). imp.reload() works similarly to importlib.reload(). Here’s an example:

>>>

>>> import hello  # First import
Hello World!
>>> import hello  # Second import, which does nothing
>>> import imp
>>> imp.reload(hello)
Hello World!
<module 'hello' from '/home/username/hello.py'>

In Python 2.x, reload() is a built-in function. In versions 2.6 and 2.7, it is also included in imp, to aid the transition to 3.x.

Using runpy.run_module() and runpy.run_path()

The Standard Library includes a module called runpy. In this module, you can find run_module(), which is a function that allows you to run modules without importing them first. This function returns the globals dictionary of the executed module.

Here’s an example of how you can use it:

>>>

>>> runpy.run_module(mod_name='hello')
Hello World!
{'__name__': 'hello',
    ...
'_': None}}

The module is located using a standard import mechanism and then executed on a fresh module namespace.

The first argument of run_module() must be a string with the absolute name of the module (without the .py extension).

On the other hand, runpy also provides run_path(), which will allow you to run a module by providing its location in the filesystem:

>>>

>>> import runpy
>>> runpy.run_path(path_name='hello.py')
Hello World!
{'__name__': '<run_path>',
    ...
'_': None}}

Like run_module(), run_path() returns the globals dictionary of the executed module.

The path_name parameter must be a string and can refer to the following:

  • The location of a Python source file
  • The location of a compiled bytecode file
  • The value of a valid entry in the sys.path, containing a __main__ module (__main__.py file)

Hacking exec()

So far, you’ve seen the most commonly used ways to run Python scripts. In this section, you’ll see how to do that by using exec(), which is a built-in function that supports the dynamic execution of Python code.

exec() provides an alternative way for running your scripts:

>>>

>>> exec(open('hello.py').read())
'Hello World!'

This statement opens hello.py, reads its content, and sends it to exec(), which finally runs the code.

The above example is a little bit out there. It’s just a “hack” that shows you how versatile and flexible Python can be.

Using execfile() (Python 2.x Only)

If you prefer to use Python 2.x, you can use a built-in function called execfile(), which is able to run Python scripts.

The first argument of execfile() has to be a string containing the path to the file you want to run. Here’s an example:

>>>

>>> execfile('hello.py')
Hello World!

Here, hello.py is parsed and evaluated as a sequence of Python statements.

How to Run Python Scripts From an IDE or a Text Editor

When developing larger and more complex applications, it is recommended that you use an integrated development environment (IDE) or an advanced text editor.

Most of these programs offer the possibility of running your scripts from inside the environment itself. It is common for them to include a Run or Build command, which is usually available from the tool bar or from the main menu.

Python’s standard distribution includes IDLE as the default IDE, and you can use it to write, debug, modify, and run your modules and scripts.

Other IDEs such as Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you to run Python scripts from inside the environment.

Advanced text editors like Sublime Text and Visual Studio Code also allow you to run your scripts.

To grasp the details of how to run Python scripts from your preferred IDE or editor, you can take a look at its documentation.

How to Run Python Scripts From a File Manager

Running a script by double-clicking on its icon in a file manager is another possible way to run your Python scripts. This option may not be widely used in the development stage, but it may be used when you release your code for production.

In order to be able to run your scripts with a double-click, you must satisfy some conditions that will depend on your operating system.

Windows, for example, associates the extensions .py and .pyw with the programs python.exe and pythonw.exe respectively. This allows you to run your scripts by double-clicking on them.

When you have a script with a command-line interface, it is likely that you only see the flash of a black window on your screen. To avoid this annoying situation, you can add a statement like input('Press Enter to Continue...') at the end of the script. This way, the program will stop until you press Enter.

This trick has its drawbacks, though. For example, if your script has any error, the execution will be aborted before reaching the input() statement, and you still won’t be able to see the result.

On Unix-like systems, you’ll probably be able to run your scripts by double-clicking on them in your file manager. To achieve this, your script must have execution permissions, and you’ll need to use the shebang trick you’ve already seen. Likewise, you may not see any results on screen when it comes to command-line interface scripts.

Because the execution of scripts through double-click has several limitations and depends on many factors (such as the operating system, the file manager, execution permissions, file associations), it is recommended that you see it as a viable option for scripts already debugged and ready to go into production.

Conclusion

With the reading of this tutorial, you have acquired the knowledge and skills you need to be able to run Python scripts and code in several ways and in a variety of situations and development environments.

You are now able to run Python scripts from:

  • The operating system command-line or terminal
  • The Python interactive mode
  • The IDE or text editor you like best
  • The file manager of your system, by double-clicking on the icon of your script

These skills will make your development process much faster, as well as more productive and flexible.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Running Python Scripts

When you execute a script without typing «python» in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:

    C:\>assoc .py
    .py=Python.File

Next, you need to know how Windows is executing things with that extension. It’s associated with the file type «Python.File», so this command shows what it will be doing:

    C:\>ftype Python.File
    Python.File="c:\python26\python.exe" "%1" %*

So on my machine, when I type «blah.py foo», it will execute this exact command, with no difference in results than if I had typed the full thing myself:

    "c:\python26\python.exe" "blah.py" foo

If you type the same thing, including the quotation marks, then you’ll get results identical to when you just type «blah.py foo». Now you’re in a position to figure out the rest of your problem for yourself.

(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)

Brought In From Comments:

Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the

HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command

key to:

"C:\Python26\python26.exe" "%1" %*

Likely, previously, %* was missing. Similarly, set

 HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/

example registry setting for python.exe
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command The registry path may vary, use python26.exe or python.exe or whichever is already in the registry.

enter image description here
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

If you cannot run or execute a python script, there is no point in being a programmer. I mean, the ultimate goal of a developer is to write scripts that are executable and actionable. You see, whenever you run a python script, the IDE converts the syntax into instructions that the computer can understand and act on. Technically, this is doable in two ways.

  1. Using the interactive python shell or
  2. Calling the interpreter using a shebang line.

Under which environments can I run a python script?

Typically, python developers write stand-alone scripts that can only be executed under certain environments. These scripts are then saved with a “.py” extension so that the operating system can identify them as python files. Once the interpreter is invoked, it identifies the script, reads it and then interprets it accordingly. However, the way python scripts are executed on Linux is different from the way they are “Run” on Windows or Mac. Confusing? Well, if you are a greenhorn in the game of coding, the whole idea can become confounding. Fortunately, we’ve got you covered. In this post, we are going to iron things out by showing you the difference in these systems and also teach you how to run a python script on Windows, Mac, and UNIX platforms. Read on!

How to run a python script on command line

Python is one of the simplest and most executable programming languages used by greenhorns as they make baby steps into the world of coding. And though a variety of applications can be used to create and execute python scripts, it is a little-known fact that windows command line can run these same programs regardless of the development method or tool used to create them. Technically, a command line prompt can be effortlessly launched from your computer’s start menu. Under most windows versions, the menu selection process is: Start ‣ Programs ‣ Accessories ‣ Command Prompt. Another option is entering ‘cmd’ in the menu search box. After successfully launching the command, the following window should appear.

C :\>

Depending on where your system files are stored, the letter that appears might be different. For instance, you might get something like:

D:\YourName\Projects\Python>

Once this command prompt window has been launched, you will be on your way to running python scripts. However, for python scripts to be executable, they have to be processed by a python interpreter. The role of this interpreter is to read the script, compile it into bytecodes, execute the bytecodes and subsequently run the program.

But how do you navigate the interpreter on the command prompt so that it can process your script?

Well, first and foremost, ensure that your command prompt recognizes the word “python” as a command to launch the interpreter. If you already have a command prompt window open, key in the command python and press enter.

C:\Users\YourName> python

If successfully done, you should get the following result depending on the version of python you are using.

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32

Type «help», «copyright», «credits» or «license» for more information.

>>>

This indicates that you have launched the interpreter in “interactive mode”. From now on, you can key in python commands, expressions, and scripts interactively and have them run as you wait. This interactive mode is one of Python’s most iconic feature. Most programmers use it as a convenient and highly programmable calculator. You can try it out by typing a few commands of your choice and see what happens.

>>> print(«Hello»)

Hello

>>> «Hello»*3

‘HelloHelloHello’

When it’s time to end your interactive session, press the “control” key, enter “z” and press “Enter” to return to your windows command prompt window.

If your computer has a start menu as Start ‣ Programs ‣ Python 3.3 ‣ Python (command line) which opens up a command prompt >>> on a new window, it will also disappear after pressing the Ctrl and Z buttons. The thing is, your system only runs one “python” command which stops all windows after ending your interactive session with the interpreter.

Possible errors and how to solve them

If the python command gives you the following error messages instead of launching the interpreter prompt >>>

‘python’ is not recognized as an internal or external command, operable program or batch file.

Bad command or filename

double check if your computer knows where to find the interpreter. To achieve this, you have to modify the list of directories (PATH) where windows gets programs before launching them. Go ahead and add python’s entire installation directory to the path of every command window. If you are not sure where you installed python, the following command will help you find out.

dir C:\py*

The most typical location should look like C:\Python33. If that’s not your case, you might have to search the entire disk. However, you can avoid it by using the search button. Type “python.exe” in the search box. If it is installed in the following directory, C:\Python33 (which is normally the default setting at the time of installation) make sure that when you execute the following command

c:\Python33\python

It launches the interpreter as shown at the beginning of this guide. If the search results indicate that the installation directory is not part of the system path, add it so that it can be possible to launch the interpreter after running the python command. Once the directory is verified, launching the python interpreter should not be a problem again. Do not also forget that you will need to press the control and Z keys to terminate the session. Once you have verified that the

How to run a python script on Windows

  1. First and foremost, create a folder where you are going to be storing your python scripts. It has to be saved in a format that windows can understand that it is a python file. For instance, you can have C:\pythonscripts as your folder name. After the folder is ready, go ahead and save your script in it. For example, hello.py.
  2. From the start menu, click “Run” the type cmd on the search box. This command is going to open the windows terminal.
  3. If your python directory is not saved in a location that windows can find it, type cd \pythonscripts to modify the PATH of your folder then press enter.
  4. Type in the name of your python script and press enter to run your script. In my case, I am going to type hello.py because it is the name of my script.
  5. If any of these steps fail to work, double check and ensure that your computer’s PATH contains the python directory so that windows can know where to get it from.

How to run a python script on Mac

  1. Like on windows, create a dedicated folder where you will be storing your python programs. For instance, you can decide to call it pythonprograms. Be sure to store it under your home folder which contains your Music, movies pictures, and other documents. Save your python script in this folder and make sure it is saved in such a way that Mac understands that it a python file. For this tutorial, we are going to be saving our script as hello.py
  2. After saving your script, launch the applications folder, open the utility folder and select the terminal program.
  3. Key in the name of the folder that contains the python script and press enter. In our case, it is going to be cd pythonprograms. This command will change the directory of the folder so that the OS can locate and execute it.
  4. Type in the name of the script to run it. For this tutorial, it is going to be python ./hello.py

NB: Most Mac computers come preinstalled with python 2 and 3. if this is the case, you should always use python3 hello.py.

How to run a python script on Linux

  1. Create a dedicated folder which is going to store your python scripts and programs. The format should be in such a way that your Linux OS can identify the file as s python file. An ideal name for the folder can be cd ~/pythonpractice. After creating the folder, save your script in that folder. Ours will be named hello.py.
  2. Launch the terminal program. Under KDE, click on the main menu then select “Run command”. This is going to open up the console. In GNOME launch the main menu and select the applications folder then open it up. Go ahead and open up the accessories folder and click on “terminal”.
  3. Change the directory of the folder containing your scripts by typing in the following command cd ~/pythonpractice. This ensures that the Linux OS can find the script when executing it.
  4. Unlike in other operating systems, you have to make it executable in Linux. This is achieved by executing the following command chmod a+x hello.py.
  5. After making sure that it is executable, type in the name of the script to run. In our case, we are going to type python ./hello.py

NB: If version 2.61 and 3.0 are both installed in your computer, you should always run python3 hello.py.

How to run a python script on Linux (advanced)

  1. Like in the previous scenarios, you still have to create a dedicated folder that is going to house your python script. The folder name should be in this format ~/pythonpractice.
  2. Launch your text editor and create a new script called hello.py, it should contain only two lines of syntax. If you want, you can copy paste it.
    	#! /usr/bin/python
    	print('Hello, world!')
    	
  3. Save this script in the ~/pythonpractice folder you previously created.
  4. Launch the terminal program. Under KDE, click on the main menu then select “Run command”. This is going to open up the console. In GNOME launch the main menu and select the applications folder then open it up. Go ahead and open up the accessories folder and click on terminal.
  5. Change the directory of the folder containing your scripts by typing in the following command cd ~/pythonpractice. This ensures that the Linux OS can find the script when executing it.
  6. Unlike in other operating systems, you have to make it executable in Linux. This is achieved by executing the following command chmod a+x hello.py.
  7. Key in ./hello.py to run your script.
  8. Alternatively, you can key in this command ln -s hello.py /usr/bin/hello to create a link between /usr/bin and hello.py under hello then execute by using the command hello.

This advanced process should only be used to execute completely compiled programs. If you regularly use your script, it will be ideal if you can store it in your home directory and link it using /usr/bin. And if you want to play around with the commands, it will be fun to invoke mkdir ~/.local/bin then transfer your scripts to this location. To make these scripts executable in a similar manner that /usr/bin does, key in this command $PATH = $PATH:~/local/bin

NB: file extensions are not necessary under UNIX file systems. In Linux, hello.py simply means what Hello.mp3 or hello means. Normally, the Linux OS uses the contents of a file to determine what type it is, unlike in windows and Mac where you have to specify file type by adding an extension.

How to run a python script in python shell

The python shell not only interprets commands line by line and executes them instantly, but also gives you the autonomy to run them over and over again whenever you wish to. It gives you the freedom to save your entire script in a python format, then run it on the python shell. But how?

STEP-1

Launch the IDLE editor. It should be available under the All Programs section in windows. After double-clicking on it, a python shell should appear as shown in the picture below.

STEP-2:

Select the file menu then click on “New file”

Simultaneously pressing the CTRL and N keys will also open an untitled and empty document editor as illustrated below. (Shortcut)

STEP-3

Write or paste your program on this editor window. If you have already saved yours, please jump to step 5.

STEP-4

After you’re done with your script or program, click on the file menu then select save. Make sure that the script is saved in a location that you can remember. You should get something like this after saving. The top section should show you where the document has been saved.

STEP-5

Launch a command window then navigate to the location where you have stored your file. In my case, I am going to type the following command.

cd c:\PythonSnippets

(Or)

I also have the alternative of using windows explorer to get my script. Press the shift button and right click to launch the open command window. You can then go ahead and open the folder containing the script.

STEP-6

On the command window/prompt that appears on your computer screen, key in the following command and press enter. This will depend on the way you have saved your script. In my case, I will have,

python AddTwoNumbers.py

Calling out the name of your script should execute your python script.

An alternative

Instead of following the whole process from the first to the last step, everything can be completed in step 3. On this Step, the script can be directly saved by pressing F5 on the editor, then it will run the program itself.

When using the live interpreter to run a python script, it is important to understand that understand that every command is read and integrated in real time. For instance, calculations will be solved immediately while loops will iterate immediately unless they are part of a function. For this reason, you have to be mentally prepared to use it. The python shell is popular with people who like executing their code interactively. However, if you want to use it to run your scripts, you have to call the Python executable or import it.

A crucial operation you need to be aware of when programming is to run a Python script.

Although this seems like a simple operation, most beginners often face difficulty when running scripts.

In this article, we will guide you through the process of running scripts in Python using different methods and environments.

To run a Python script, you must:

  1. Open a Terminal or Command Prompt Window
  2. Navigate to the directory where your Python script (.py file) is located using the ‘cd’ command
  3. Execute your script by typing ‘python’ followed by the name of your script

How to Run a Python Script

There are multiple ways to run a script, and by the end of this article, you’ll have a solid understanding of how to run Python scripts in different environments and operating systems.

Understanding each method can improve your programming experience and help you adapt to different scenarios.

Let’s get into it!

6 Methods to Run a Python Script

In this section, we will cover 6 ways of running a Python Script.

Specifically, we will go over the following:

  1. Running a Python Script From Command Line
  2. Running a Python Script From Python Interactive Shell
  3. Running a Python Script in IDE
  4. Running a Python Script in IDLE
  5. Running a Python Script Using Import
  6. Running a Python Script Using runpy.run_module() And runpy.run_path()

6 Ways to Run Python Scripts

1) How to Run a Python Script From Command Line

The process of running a Python script from the command line is quite similar across different operating systems.

In this section, we will look at how you can:

  1. Run Python scripts from the command line on Windows
  2. Run Python scripts from the command line on Linux and MacOS

1) How to Run Python Scripts From The Command Line on Windows

You can use the following steps to run a Python program from the command line on Windows:

Step 1: Open the Command Line Interface. You can do this by searching for cmd in the start menu or by pressing Win+R, typing cmd, and then hitting Enter.

Opening Command Prompt

Step 2: Navigate to the directory containing your Python script using the cd command.

For example, if your script is in a directory on your local drive E in a folder named “PythonScripts”, you would type cd E\PythonScripts.

Navigating to file directory

Step 3: Run the script by typing python script.py (replace script.py with the name of your script), and press Enter.

Running Python script

2) How to Run Python Scripts From The Command Line on Linux And MacOS

Follow the steps listed below to run Python scripts from the command line on Linux and MacOS:

Step 1: Open the terminal.

Step 2: Navigate to the directory containing your Python script using the cd command.

For example, if your script is in a directory in your home folder named “PythonScripts”, you would type cd ~/PythonScripts.

Step 3: To run your script, type python3 script.py (replace script.py with the name of your script), and press Enter.

2) How to Run Python Script From Python Interactive Shell

The Python Interactive Shell, also known as the Python Interpreter, is an excellent tool for trying out small snippets of Python code and doing simple calculations, but it’s not the best tool for running large, complex scripts.

However, if you want to run a Python script from the Python Interactive Shell, you can do so using Python’s built-in execfile() function in Python 2, or using the exec() function with open() in Python 3.

Running Python Script From Python Interactive Shell

Running a Python Script in Python 2

Follow the steps below to run a script from the Python interactive shell in Python 2:

Step 1: Open the Python Interactive session by typing python into your terminal or command prompt and hitting Enter.

Step 2: Type execfile(‘script.py’), replacing ‘script.py’ with the path to your script.

For example:

>>> execfile('C:/Users/username/Desktop/script.py')

Running a Python Script in Python 3

In Python 3, the execfile() function has been removed. Instead, you can use exec() with open() to achieve the same effect.

Follow the steps below to run a script in Python 3:

Step 1: Open the Python Interactive Shell by typing python3 (or python if Python 3 is your default Python) into your terminal or command prompt and hitting Enter.

Step 2: Type the following, replacing ‘script.py’ with the path to your script.

>>> exec(open('C:/Users/username/Desktop/script.py').read())

The output for the above execution will be:

Running a Python Script in Python 3

3) How to Run a Python Script in IDE

You can run Python scripts in different Integrated development environments, and each has its own way of executing scripts.

For instance, if you’d like to run a Python script in VS Code, you can follow the steps given below:

Step 1: Launch Visual Studio Code, and open your Python file (File > Open File…).

If you haven’t created a Python file yet, create a new file (File > New File), and make sure to save it with a .py extension.

Step 2: Select a Python interpreter by clicking on the Python version in the bottom left of the status bar, or use the command palette (Ctrl+Shift+P) and search for “Python: Select Interpreter”.

This will show a list of available interpreters that VS Code can find automatically, including virtual environment interpreters.

Selecting an interpreter

Step 3: Once you have written your Python script and selected the Python interpreter, you can open a new terminal in VS Code to execute the script.

Running a Python Script in IDE

If you are using a Python virtual machine, you can use the same steps as discussed above after creating a virtual environment.

4) How to Run Python Script in Python’s IDLE

Python’s IDLE (Integrated Development and Learning Environment) is a simple IDE that comes with Python.

To run a Python script in IDLE, you can follow the steps given below:

Step 1: You can launch Python IDLE from your Start Menu (Windows), Applications folder (macOS), or application launcher (Linux).

Simply search for IDLE and click on the icon.

Opening IDLE

Step 2: Once IDLE is open, you can load your Python script into the IDLE text editor. Go to File > Open… in the menu bar.

Navigate to your Python script in the file dialog, select it, and click Open.

Step 3: After the script is loaded into the IDLE text editor, you can run it by going to Run > Run Module in the menu bar, or simply by pressing the F5 key.

Running the script

Step 4: The output from your script will be displayed in the Python Shell window.

If your script includes input calls like input(), the shell will also provide a prompt for user input.

Output of the script

5) How to Run a Python Script Using Import

Running a Python script using import essentially involves treating the script as a module.

When you import the script, Python will execute it from top to bottom, just as if you’d run the script directly.

Suppose you have a Python script named myscript.py with the following content:

# myscript.py

def greet():
    print("Hello from myscript!")

print("This will be printed upon import!")

You can run the script by importing it.

Open the Python shell by typing python or python3 (depending on your installation) in the terminal. Navigate to the directory containing myscript.py or make sure myscript.py is in a directory that’s part of your PYTHONPATH.

Import myscript with the following code:

>>> import myscript

The output of this execution will be:

Running a Python Script Using Import

6) How to Run a Python Script Using runpy.run_module() And runpy.run_path()

The runpy module in Python allows you to execute Python code dynamically.

It contains two main functions, run_module() and run_path(), which can be used to run Python scripts.

1) runpy.run_module()

The run_module() function allows you to execute a Python module without importing it.

It runs the module as if it was invoked from the command line using the -m option.

The following is an example of this method:

import runpy

# Run a standard library module as a script
# Equivalent of running "python -m http.server" from the command line
runpy.run_module(mod_name='http.server', run_name='__main__', alter_sys=True)

In this example, the http.server module from the Python standard library is being run, which will start a simple HTTP server.

2) runpy.run_path()

The run_path() function allows you to execute a Python script located at a specific path.

It reads and runs the Python file specified as the path.

The following is an example of run_path():

import runpy

# Run a script file as a standalone script
runpy.run_path('path_to_script.py', run_name='__main__')

In this example, replace ‘path_to_script.py’ with the actual path to your Python script.

This will execute the script just like running python path_to_script.py from the command line.

Running a Python Script Using  runpy.run_path()

Supercharge your analytics game with Code Interpreter by watching the following video:

Final Thoughts

Mastering the various ways to run a Python script is an invaluable skill for any programmer. It allows you to test and execute your code across diverse platforms and environments.

By learning these techniques, you’ll find that you have more flexibility and control in your development process, whether it’s running scripts from the command line, an IDE, or even using Python’s own tools like import and runpy.

Each method discussed offers unique benefits, be it the simplicity of running scripts in an IDE, the powerful control provided by command-line execution, or the dynamic capabilities of the import statement and runpy.

Frequently Asked Questions

In this section, you will find some frequently asked questions you may have when running Python scripts.

Male Programmer writing Python code

How do I execute a Python script in terminal?

To execute a Python script in the terminal, simply type python followed by the file name, including the “.py” extension.

For example, to run a script called “script.py”, you would type:

python script.py

What is the command to run a Python script from the command line?

The command to run a Python script from the command line is the same as executing it in the terminal.

Use python followed by the file name with the “.py” extension.

For instance:

python script.py

How can I run a .py file in Windows?

To run a .py file in Windows, open the Command Prompt and navigate to the directory containing the .py file.

Then, use the command python followed by the file name with the “.py” extension.

For example:

python script.py

What are the steps to run a Python script in a specific folder?

To run a Python script in a specific folder, follow these steps:

  1. Open the terminal or command prompt.
  2. Navigate to the folder containing the .py file using the cd command. For example:
cd path/to/your/script-folder
  1. Run the Python script using the python command followed by the file name:
python script.py

How can I execute Python code in Visual Studio Code?

To execute Python code in Visual Studio Code, follow these steps:

  1. Open the Python file in Visual Studio Code.
  2. Ensure that the Python extension is installed and correctly configured.
  3. Click the “Run” button in the top-right corner, or right-click in the editor and select “Run Python File in Terminal”.

Is it possible to run a Python script in the background?

Yes, it is possible to run a Python script in the background. This can be achieved using various methods, such as appending an ampersand (&) to the command in Unix-like systems or using the start command in Windows.

For example:

  • On Unix-like systems:
python script.py &
  • On Windows:
start python script.py

Python is a programming language as well as a scripting language because it has both an interpreter and a compiler. Programs are compiled while scripts are interpreted. Many operating systems support Python such as Windows, Linux, etc.

This article will demonstrate the method of running Python Script on Windows.

What is a Python Script?

A program saved in a simple text file that comprises Python code (logical sequence of instructions) is called a Python script.

What is a Python Interpreter?

The interpreter functions as a software layer that serves communication between a program and ensures the smooth execution of code. Python scripts are executed by a Python interpreter. The interpreter first reads the code, then processes the code, and finally prints the code.

Let’s see some different methods of running Python Script on Windows.

To run a Python script on Windows, use one of the following techniques:

  1. Using Command Prompt
  2. Using File Manager
  3. Using Python IDE

Method 1: Use Command Prompt to Run the Python Script 

We can run Python scripts in Windows easily with the help of a Command Prompt (also known as a Command-line Interpreter). Simply go to Windows search and type cmd to launch the Command Prompt.

Type Python in the terminal and press the ENTER key to start a Python session.

Now you can start using Python. Let’s play around with a few examples as shown below: 

To exit the interactive session, type quit() or exit() as shown below:

This is the simplest yet easiest method of running scripts in Python.

Note: It has some disadvantages like the Python scripts are not saved. If you end the session and start a new one, you will have to start everything from scratch. Hence this method is not recommended for working on projects.

Method 2: Use File Manager to Run Python Script on Windows

To run a Python script using File Manager, go to the folder where you have saved your file as demonstrated below:

Type cmd in the search box of the folder as shown below:

Now type Python and the name of the file with .py extension. In my case, the name of the file is script.py as illustrated below:

The Program is executed successfully and the output is displayed.

Note: This method could be convenient sometimes but this method is not preferred by developers.

Method 3: Use IDE to Execute Python Script on Windows

IDE is a software application that helps developers to create programs quickly and smoothly An IDE is composed of a source code editor, debugger, etc. There are numerous free and open-source Python IDEs available to use like Spyder, PyCharm, Thonny, etc.

I have already downloaded and installed Thonny. Let’s do an example in Thonny:

marks = eval(input("Enter a number: "))
if marks>=90:
    print("Congratulations! You have passed the exams with A grade")
elif marks>=80:
    print("You have passed the exams with B grade")
elif marks>=70:
    print("You have passed the exams with C grade")
elif marks>=60:
    print("You have passed the exams with D grade")
elif marks>=50:
    print("You have passed the exams with D grade")
else:
    print("Hard luck! , you couldn't pass the exams")

Type in the code in the Thonny editor and click the “Run” button or press the F5 key to get the desired results from the Python script:

The shell is provided below where the output is displayed.

Conclusion

A program saved in a simple text file that is composed of Python code is called a Python script. There are various methods of running a Python script on Windows. The first method of running scripts in Python is by using Command Prompt, the second method is by using a file manager and the final method is by using IDE.

  • Run program as windows service
  • Rundll возникла ошибка при запуске c windows system32 logilda dll не найден указанный модуль
  • Runtime broker что это за процесс windows 10 как отключить
  • Run powershell script from windows powershell
  • Run в windows 10 как вызвать