Windows run python from command line

Whether you're writing Python code on your Windows PC or just want to use existing Python scripts, it'll be helpful to learn how to run code from the Command Prompt. Running Python code is easy—you'll just need to have Python installed....


Download Article


Download Article

Whether you’re writing Python code on your Windows PC or just want to use existing Python scripts, it’ll be helpful to learn how to run code from the Command Prompt. Running Python code is easy—you’ll just need to have Python installed. This wikiHow article will walk you through opening a Python file from Command Prompt, and teach you how to fix the common «python is not recognized as an internal or external command» error.

  1. Image titled Use Windows Command Prompt to Run a Python File Step 1

    1

    Go to the Python file’s location. Find the Python file that you want to open in Command Prompt.

    • If you already know the folder path to the Python file you want to open, skip ahead to opening the file in Command Prompt.
  2. Image titled Use Windows Command Prompt to Run a Python File Step 2

    2

    Select the Python file. Click once the Python file for which you want to see the folder path.

    Advertisement

  3. Image titled Use Windows Command Prompt to Run a Python File Step 3

    3

    Right-click the Python file. Doing so prompts a drop-down menu to appear.

  4. Image titled Use Windows Command Prompt to Run a Python File Step 4

    4

    Click Properties. It’s in the drop-down menu. The properties window will open.

  5. Image titled Use Windows Command Prompt to Run a Python File Step 5

    5

    Note the «Location» value. The folder address (or «path») to the right of the «Location» heading is what you’ll need to enter into Command Prompt when switching to the directory in which your Python file is stored.

    • You can copy the location by highlighting it (click and drag your mouse across the «Location» value) and then pressing Ctrl+C.
  6. Advertisement

  1. Image titled Use Windows Command Prompt to Run a Python File Step 6

    1

    Open Start

    Image titled Windowsstart.png

    . Click the Windows logo in the bottom-left corner of the screen. The Start menu will pop up.

  2. Image titled Use Windows Command Prompt to Run a Python File Step 7

    2

    Search for Command Prompt. Type in cmd to do so.

  3. Image titled Use Windows Command Prompt to Run a Python File Step 8

    3

  4. Image titled Use Windows Command Prompt to Run a Python File Step 9

    4

    Switch to your Python file’s directory. Type cd and a space, then type in the «Location» address for your Python file and press Enter.

    • For example, to open a Python file in a folder named «Files» on your Desktop, you would enter cd desktop/Files here.
    • If you copied the path to the file, you can type in cd and a space and then press Ctrl+V to paste in the path.
  5. Image titled Use Windows Command Prompt to Run a Python File Step 10

    5

    Enter the «python» command and your file’s name. Type in python file.py where file is your Python file’s name.

    • For example, if your Python file is named «script», you would type in python script.py here.
    • If your Python file has one or more spaces in its name, you’ll place quotation marks around the file name and extension (e.g., python "my script.py").
  6. Image titled Use Windows Command Prompt to Run a Python File Step 11

    6

    Press Enter. Doing so runs your command and opens your Python file via your computer’s installed Python program.

    • If you encounter an error that says 'python' is not recognized as an internal or external command after pressing Enter, you’ll need to add Python to the PATH list before retrying this part.
  7. Advertisement

  1. Image titled Use Windows Command Prompt to Run a Python File Step 12

    1

    Enable viewing for hidden folders. Since one of the folders that contains your Python installation folder is most likely hidden, you’ll have to unhide it before proceeding:

    • Open File Explorer
      Image titled File_Explorer_Icon.png

      .

    • Click the View tab.
    • Check the «Hidden items» box.
  2. Image titled Use Windows Command Prompt to Run a Python File Step 13

    2

    Navigate to your Python folder. In some cases, the Python path is «C:Python27»; however, if you’ve installed the most recent version of Python using the default settings, it’s tucked away in a hidden folder. You can copy the proper file path by doing the following:

    • Click This PC on the left side of the File Explorer.
    • Double-click your hard drive in the «Devices and drives» section.
    • Scroll down and double-click the «Users» folder.
    • Double-click the folder with your username on it.
    • Scroll down and double-click «AppData».
    • Double-click «Local».
    • Scroll down and double-click «Programs».
    • Double-click the «Python» folder.
    • Double-click the Python folder with your preferred version number (e.g., «Python36»).
  3. Image titled Use Windows Command Prompt to Run a Python File Step 14

    3

    Copy the path to the Python folder. Click once the address bar at the top of the File Explorer to highlight its contents, then press Ctrl+C to copy the highlighted address.

  4. Image titled Use Windows Command Prompt to Run a Python File Step 15

    4

    Open the Power User menu. Right-click the Start

    Image titled Windowsstart.png

    icon to do so. You should see a pop-up menu appear.

    • You can also press Win+X to open the Power User pop-up menu.
  5. Image titled Use Windows Command Prompt to Run a Python File Step 16

    5

    Click System. It’s in the pop-up menu. A new window will open.

  6. Image titled Use Windows Command Prompt to Run a Python File Step 17

    6

    Click System info. This is a link in the upper-right corner of the window. Doing so opens the System Information window.

  7. Image titled Use Windows Command Prompt to Run a Python File Step 18

    7

    Click the Advanced system settings link. You’ll see this in the upper-left side of the System Information window. Yet another window will pop up.

  8. Image titled Use Windows Command Prompt to Run a Python File Step 19

    8

    Click Environment Variables…. It’s in the bottom-right corner of the pop-up window.

  9. Image titled Use Windows Command Prompt to Run a Python File Step 20

    9

    Find the «Path» heading in the «User variables» pane. This window is at the top of the Environment Variables window.

    • You may have to scroll up or down with your mouse cursor hovering over the «User variables» pane to find the «Path» variable.
  10. Image titled Use Windows Command Prompt to Run a Python File Step 21

    10

    Double-click the «Path» heading. Doing so opens a pop-up window.

  11. Image titled Use Windows Command Prompt to Run a Python File Step 22

    11

    Click New. It’s on the right side of the window. A text field will open in the middle of the window.

  12. Image titled Use Windows Command Prompt to Run a Python File Step 23

    12

    Paste in your copied path. Press Ctrl+V to do so. Your copied path will appear in the text field in the middle of the window.

  13. Image titled Use Windows Command Prompt to Run a Python File Step 24

    13

    Click OK on the three open windows. This will save your changes and close the «Path» window, the «Environmental Variables» window, and the «System Properties» window.

  14. Advertisement

Add New Question

  • Question

    I want to create a shortcut that executes the utility «ptpython,» running in the cmd prompt. The shortcut I have points to the directory containing «ptpython.exe» file but it does not execute it.

    Community Answer

    It sounds like ptpython.exe is a command-line utility, meaning it will only start if you execute it from a DOS window — you can’t create a shortcut for it directly. You can probably create a shortcut to cmd.exe, though (the DOS window) and pass it the ptpython.exe file as a parameter. Something like «cmd.exe /c ptpython.exe» should work, or if this disappears in the end, try with /k (instead of /c).

  • Question

    Does this work on Windows 7?

    Arrogance

    Yes. The directions to access the environment variables would be slightly different, as there is no «Power User» menu in Windows 7. Instead: 1. Press the Windows key and R to open the Run dialog. 2. Enter «sysdm.cpl». 3. Click the «Advanced» tab of the System Properties Window. 4. Click the «Environmental variables». Most everything else would work as described even on Windows 95 (if there’s a version of Python for Windows 95).

  • Question

    After opening the Command Prompt and navigation to the directory in which the py file exists and opening Python, not able to run the file using python file_name.py. It says that the syntax is wrong.

    Arrogance

    That sounds like a problem with the file you’re trying to run. Make sure you are using the right version of Python for it (version 2 or 3, usually).

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Thanks to all authors for creating a page that has been read 718,311 times.

Is this article up to date?

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

It has taken me some effort looking for answers here, on the web, and and in the Python documentation, and testing on my own, to finally get my Python scripts working smoothly on my Windows machines (WinXP and Win7). So, I just blogged about it and am pasting that below in case it’s useful to others. Sorry it’s long, and feel free to improve it; I’m no expert.

[UPDATE: Python 3.3 now includes the Python Launcher for Windows, which allows you to type py (rather than python) to invoke the default interpreter, or py -2, py -3, py -2.7, etc. It also supports shebang lines, allowing the script itself to specify. For versions prior to 3.3, the launcher is available as a separate download.
http://docs.python.org/3/whatsnew/3.3.html
]

Running Python scripts conveniently under Windows

Maybe you’re creating your own Python scripts, or maybe someone has given you one for doing something with your data files. Say you’ve acquired a Python script and have saved it to «D:my scriptsApplyRE.py». You want to run it conveniently by either double-clicking it or typing it into the command line from any location, with the option of passing parameters to it like this (-o means «overwrite the output file if it already exists»):

ApplyRE infile.txt outfile.txt -o

Say you also have a data file, «C:some filessome lexicon.txt». The simplest option is to move the file or the script so they’re in the same location, but that can get messy, so let’s assume that they’ll stay separate.

Making sure Windows can find the Python interpreter

After installing Python, verify that typing python into a command prompt works (and then type exit() to get back out of the Python interpreter).

C:>python
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
C:>

If this doesn’t work, you’ll need to append something like «;C:Python32» (without quotes) to the PATH environment variable. See PATHEXT below for instructions.

Associating Python with .py and .pyc

Verify that double-clicking on ApplyRE.py runs it. (It should also have a Python logo as its icon and be labeled «Python File», by the way.) If this isn’t already done, right-click on a .py file, choose Open With, Choose Program, and check «Always use…» This association improves convenience but isn’t strictly necessary—you can specify «python» every time you want to run a script, like this:

D:my scripts>python ApplyRE.py lexicon-sample.txt -o
Running... Done.

Here’s a very specific variation, which is optional unless you need to specify a different version of the interpreter.

D:my scripts>c:python32python ApplyRE.py lexicon-sample.txt -o
Running... Done.

But that’s a pain. Fortunately, once Python is installed, in the PATH, and associated with .py, then double-clicking a .py file or directly typing it as a command should work fine. Here, we seem to be running the script directly—it’s nice and simple to run it on a sample file that’s located in the «my scripts» folder along with the script.

D:my scripts>ApplyRE.py lexicon-sample.txt -o
Running... Done.

Omitting the .py extension (editing PATHEXT)

To further reduce typing, you can tell Windows that .py (and perhaps .pyc files) are executable. To do this, right-click Computer and choose Properties, Advanced, Environment Variables, System Variables. Append «;.PY;.PYC» (without quotes) to the existing PATHEXT variable, or else create it if you’re certan it doesn’t exist yet. Close and reopen the command prompt. You should now be able to omit the .py (FYI, doing so would cause ApplyRE.exe or ApplyRE.bat to run instead, if one existed).

D:my scripts>ApplyRE lexicon-sample.txt -o
Running... Done.

Adding scripts to the system PATH

If you’re going to use your scripts often from the command prompt (it’s less important if doing so via using BAT files), then you’ll want to add your scripts’ folder to the system PATH. (Next to PATHEXT you should see a PATH variable; append «;D:my scripts» to it, without quotes.) This way you can run a script from some other location against the files in current location, like this:

C:some files>ApplyRE "some lexicon.txt" "some lexicon OUT.txt" -o
Running... Done.

Success! That’s pretty much all you need to do to streamline the command-line.

Running directly without tweaking the PATH

If you’re a fast typist or don’t mind creating a batch file for each situation, you can specify full paths (for the script, or for the parameters) instead of tweaking PATH.

C:some files>"d:my scriptsApplyRE.py" "some lexicon.txt" "some lexicon OUT.txt" -o
Running... Done.
C:some files>d:
D:>cd "my scripts"
D:my scripts>ApplyRE.py "c:some filessome lexicon.txt" "c:some filessome lexicon OUT.txt" -o
Running... Done.

Creating shortcuts or batch files

If .py is associated with an installed Python, you can just double-click ApplyRE.py to run it, but the console may appear and disappear too quickly to read its output (or failure!). And to pass parameters, you’d need to first do one of the following.
(a) Right-click and create a shortcut. Right-click the shortcut to edit properties and append parameters to Target.
(b) Create a batch file—a plain text file with a distinct name such as ApplyRErun.bat. This option is probably better because you can ask it to pause so you can see the output. Here is a sample BAT file’s contents, written to be located and run from c:some files .

python "d:my scriptsApplyRE.py" "some lexicon.txt" "some lexicon OUT.txt" -o
pause

Advanced: appending to PYTHONPATH

This usually isn’t necessary, but one other environment variable that may be relevant is PYTHONPATH. If we were to append d:my scripts to that variable, then other Python scripts in other locations could make use of those via import statements.

Creating Python scripts that can be run from the command line makes it much easier to abstract and share your code so that it can be reused and shared with others. Running scripts from the command line can also streamline your development and analysis workflows to make them more concise and make you more productive.

It’s quite easy to run Python scripts from the command line.

  1. Verify your terminal or command prompt can run Python
  2. Create a Python script that is error-free
  3. Use python your/file/name.py to run your script from the terminal

This article will demonstrate how to get a simple Python script running on the command line in a matter of minutes. Once you’ve mastered that, you can get more complicated by passing in required arguments so that your scripts can stand on their own. Once you are comfortable running Python scripts from the command line, continue improving your skills by learning how to pass arguments to your scripts.

Make Sure Your Terminal or Command Prompt Can Run Python

To start, you need to make sure the command line application you are using has access to your Python installation. To do this, open the command prompt, type python and press ‘Enter’. You should see a message that documents the Python version that is being used followed by >>>, which indicates the next code you type will be executed by the Python interpreter. It will look something like this.

Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

If you don’t see something similar, it means that you don’t have Python installed or that the command prompt is not aware of your Python installation.

Create a Python Script

Let’s create a very simple script to demonstrate how this works. This Python script (hello.py) will simply print out a statement that lets us know the code in the script has run, as shown below.

hello.py

print("Hello from my Python script")

Once your Python script is created it’s super easy to run it from the terminal or command line. All you need to do is type python followed by the script name. You’ll need to make sure that your terminal’s working directory is the directory that contains your python script, or give the full path to the script. For example. If I just type python hello.py I get the following error.

python: can't open file 'hello.py': [Errno 2] No such file or directory

There are two ways to fix this.

First, specify the full file path. Like this.

C:UsersKonrad>python c:/konrad/code/python/z_testing/hello.py
Hello from my Python script

You can see that by specifying the full path to the python script that the terminal now knows where to find the file to run and I get the proper output.

Second, use cd to change the terminal’s current directory. Then run the script. Like this.

(base) C:UsersKonrad>cd c:/konrad/code/python/z_testing
(base) c:konradcodepythonz_testing>python hello.py
Hello from my Python script

By using cd to change the terminal’s directory I no longer need to type the full path to the python script. This is especially useful if you have a number of different scripts in the same directory that you will want to run.

There’s More!

This article gives you a brief, simple introduction to running python scripts from the terminal (or command line). This is a powerful skill to have and there is so much more you can do with it. With a more advanced script, you can pass in parameters/arguments from the command line, which makes it easy to generalize and share your scripts for others to use in various situations. You can check out my guide for passing variables to python scripts from the terminal in this article.

Whether you’re looking to take your GIS skills to the next level, or just getting started with GIS, we have a course for you! We’re constantly creating and curating more courses to help you improve your geospatial skills.

All of our courses are taught by industry professionals and include step-by-step video instruction so you don’t get lost in YouTube videos and blog posts, downloadable data so you can reproduce everything the instructor does, and code you can copy so you can avoid repetitive typing


My Recommended Equipment

Computer: Dell XPS

Mouse: Logitech M557 Bluetooth Mouse

External Hard Drive: Seagate Portable 2TB


This article contains affiliate links. When you click on links in this article Open Source Options may make a commission on any sales. This does not have any impact on the price you pay for products.

Video

Konrad Hafen

Konrad has a Master’s Degree in Ecology and a Doctorate Degree in Water Resources and has been performing geospatial analysis and writing code (in multiple programming languages) for over a decade. He writes code to develop models and analysis workflows to predict and evaluate changes to landscapes and water resources. He has published multiple articles in prominent peer-reviewed, scientific journals. Konrad’s code and workflow contribute to operational products that inform water and ecosystem management.

Latest Tutorials

link to How to Install GeoPandas and Check GeoPandas Version

link to Remote Sensing Analysis with QGIS

Remote Sensing Analysis with QGIS

In geographic information science (GIS), remote sensing is the act of acquiring information about the features of the Earth’s surface from a distance. Remotely sensed data are acquired from many…

python-on-windows

A step-by-step guide on installing Python and using the Command Prompt for Windows

  • Version: 1.1.0
  • Date: 2017-01-03
  • Author: Alberto Pettarin (contact)
  • License: Creative Commons Attribution 4.0 International (CC BY 4.0)

Overview

Do you want to run a Python program under Windows,
but you have no experience using the Command Prompt?

This guide is for you!

I will walk you through the installation of Python
and I will explain the basics of the Command Prompt.

After reading this page (and practicing a bit),
you should be able to run a Python program
confidently and safely.

What Is Python?

Python is a
high-level, general-purpose programming language
which allows people to easily create and share programs
for a variety of applications.

The Python project is a free (libre)/open source software (FLOSS) initiative,
managed by the Python Software Foundation.
You can download, install, and use Python for free
on several platforms,
including Linux, Mac OS X, and Windows computers.

Python enables the development of FLOSS programs,
which are created for free
by millions of volunteers around the globe
and shared in source code form.
This means that the end user
who receives or downloads a Python program
can actually check that the program does what
is supposed to do, and nothing more
(unlike closed-source programs,
which send personal information to third parties,
show you advertisements, or
damage your computer).

More details on Python can be found on the
official Python page
and on its
Wikipedia page.

In practice, to use a Python program you need two pieces of software:

  • the Python interpreter, which is the «master» program
    that reads the source code of a Python program,
    and «execute» it; and
  • the source code of the Python program,
    usually consisting of one or more files with .py extension,
    which performs the specific task you are interested in.

This guide explains how to install the former,
and it shows how to run the latter
in the Command Prompt of Windows,
with a complete, real-life example.

Installing Python On Windows

The preliminary step consists in installing
the Python interpreter (i.e., the «master program»)
on your computer.

Installing Python is a one-time operation.
If you already installed Python in the past
(for example, to run a different program),
you do not need to install it again,
and you can skip to the next section.

Step 0: Should I Get Python 2 Or Python 3?

At the time of writing (2017-01-01),
there are two main versions of Python:
Python 2 (2.7.13) and Python 3 (3.6.0).

Discussing the technical differences between these two versions
is beyond the scope of this guide.
It suffices to say that
some Python programs work with both versions of Python,
while other Python programs work only
with Python 2 but not with Python 3,
or vice versa.

You should get the version of Python that the program
you are interested in recommends.

If the latter does not specify a version,
get the latest Python 3 version available.
If you later discover that your Python program
does not work with the Python version you installed,
do not worry: just uninstall it, and install the other one!

In the rest of the guide we assume you need Python 3.

Step 1: Download The Installer

First, open your Web browser and
go to https://python.org/:

Python home page

Click on the Download > Latest Python 3.6.0 link.

You will get a page listing all the new features of Python 3.6.0:

Python 3.6.0 download page

Scroll down until you see the list of available downloads:

Python 3.6.0 downloads

If you have a recent Windows computer,
very likely it is a 64-bit machine,
so you should download the file labeled Windows x86-64 executable installer,
and save it on your Download folder or on your Desktop:

Python 3.6.0 downloads

Downloading the file will take from few seconds to a few minutes,
depending on the bandwidth of your Internet connection.

(If you have an older PC that you know is a 32-bit computer,
download the Windows x86 executable installer instead.
You can tell whether your PC is a 32-bit or a 64-bit machine
by reading the System Information in the Windows Control Panel.)

Step 2: Install Python

Double-click on the file you just downloaded
to start the installation wizard:

Python 3.6.0 installer

By default, the Add Python 3.6 to PATH option is disabled,
but you should select it,
as it makes running Python programs much much easier.

Most users should click the Install Now button,
which installs Python with the default settings.
(If you want to personalize your installation
or you are told to enable some advanced features,
click on the Customize installation option instead.)

The installer might ask you for administrative privileges
or for confirmations like the following:

Python 3.6.0 installer asking for confirmation

You can safely answer Yes.

A progress bar will appear:

Python 3.6.0 installer progress bar

until the installation completes with the following message:

Python 3.6.0 installer completed

Starting with Python 3.6.0,
it is recommended to click on
the Disable path length limit option,
before closing the installer.
If you do so, you will get a final confirmation dialog:

Python 3.6.0 installer completed

You can terminate the installation by clicking the Close button.

Congratulations, you have your first Python installation under your belt!

Using The Command Prompt

Most Python programs are command line interface (CLI) utilities,
which means that they are not operated
via a graphical user interface (GUI),
also known as «the program window».
Instead, they must be executed
in the Command Prompt of Windows,
also known as «shell» or «terminal».

Running a CLI program means
typing a command string on the Command Prompt of Windows,
following a certain syntax
which depends on what the program is supposed to do.
You can think of this act as reciting the «right spell»
to get your job done.

Opening A Command Prompt

To open the Command Prompt,
locate the Command Prompt icon in your Start menu
(or use the search bar):

Command Prompt icon

Click on the icon. A black window appears:

Command Prompt window

The first two lines printed in the window
show the version of the Command Prompt.
The last line, which reads C:UsersIEUser> in the screenshot above,
is the prompt, where you can actually type commands.

The prompt line always starts
with the location of the working directory,
that is, the folder where the command prompt is currently acting upon
(C:UsersIEUser in the screenshot above),
and ends with the > character.

The prompt normally opens in the home directory of the current user:
in fact, we are in C:UsersIEUser,
because the user is called IEUser.
If your Windows username is Olga,
it is likely you will see
C:UsersOlga instead.

(Different versions of Windows might have different paths for home directories.)

In the documentation of Python programs you might find a $ character
before examples of commands, as follows:

$ python my_awesome_program.py

because on Linux and Mac OS X machines
the terminal prompt is usually a $ character.

You should not type the $ character,
it is just a placeholder for your actual prompt.
For any practical purpose,
you can mentally replace the $ with your actual prompt,
like C:UsersIEUser> in the example above,
as if the documentation was as follows:

C:UsersIEUser> python my_awesome_program.py

(You will actually type only python my_awesome_program.py and
hit the Enter/Return key.)

The Three Safety Rules

By issuing commands on the Command Prompt,
you can accidentally delete your own files or damage Windows,
so you must be careful.

Do not be afraid or discouraged:
you do not stop using knives just because
you can cut your fingers with them!

By following Three Safety Rules,
you can operate the prompt safely:

  1. Never issue a command without understanding what it does,
    and only run programs obtained from developers that you trust.
  2. If anything happens in the prompt that you do not understand,
    you can simply click on the «X» on the right top corner
    to close the Command Prompt window
    (and hopefully nothing bad will happen to your files).
  3. Always copy your Python program in a separate
    folder, and always make copies of your input files in it,
    so that you can just throw away the Python program folder
    if something goes wrong, and start over.

Changing The Working Directory (cd)

As said above, the command prompt normally opens
in the home directory of your user:

Command Prompt window

If you want to change the current working directory,
you can use the cd command.
For example, to move to the C: directory
(the root directory of your C: drive),
you type cd C:
and press the Enter/Return key:

Command Prompt window

Notice that the prompt changed to C:>.

Listing The Contents Of The Working Directory (dir)

If you want a list of the files or subdirectories
contained in the current working directory,
issue the dir command, without arguments:

Command Prompt window

The prompt shows a list of directories and files
that are contained in the C: drive:
in the above screenshot they are
BGinfo, PerfLogs, …, Windows.

At this point, if you want to enter the Users directory,
you can simply type cd Users, and so on.

If you want to go up one level, type cd ..
(two full stop character).
For example, if you are in C:Users and give a cd ..,
you will end up in C:.

If you want to clear the prompt window, use the cls command.

Checking That Python Is Installed Correctly

If you selected the Add Python to PATH option,
you can run the Python interpreter (and any Python program)
from any current working directory.

To check this, give the python --version command:

Python non-interactive execution

The Python version will be printed
(e.g., Python 3.6.0)
and you will get back to the Windows prompt.
You just ran Python in non-interactive mode,
meaning that you provided a precise command
(«Python, print the version number you are»),
the Python interpreter performed what you asked for,
and then it returned control to the Command Prompt of Windows.

The non-interactive mode is how most Python programs work.

If you forget to add the --version parameter
after the python command,
you will enter the interactive Python shell instead:

Entering Python interactive shell

Notice how the prompt changed to >>>.

To exit the Python shell, and return to the Command Prompt,
just type quit() and hit the Enter/Return key:

Leaving Python interactive shell

Discussing the interactive shell is beyond the scope of this guide,
since most programs you are interested in are non-interactive.

Running A Python Program

Excellent, now you have all the tools required
to run a Python program on the command line.

As an illustration,
I will use my simple Python script
export-kobo,
which reads annotations and highlights
from the database file of a Kobo eReader device (KoboReader.sqlite),
and prints them on the prompt or exports them to an output file.

Step 1: Download The Source Code

First, download the source code of the Python program you want to run.

This usually implies downloading either a single Python source code file
(with extension .py), or a ZIP file containing several Python source code files
and other resource files that you need to uncompress somewhere on your disk.

The exact details depend on your Python program,
hence be sure to carefully read its install documentation.
You can download the prescribed files with your browser,
and then copy/uncompress them using the Windows graphical file manager.

In our example, we download the raw file
export-kobo.py
from the GitHub repository.

Remember Safety Rule 3
(«copy your Python files into a separate folder»)?

We put the downloaded export-kobo.py file
in a new folder C:export-kobo:

Running a Python program

Note that we also copied
the KoboReader.sqlite file
(the input of our Python program)
from our Kobo eReader
to the same folder.

Step 2: Open A Command Prompt And cd There

Then, open a Command Prompt as explained above,
and change the current working directory to the folder
where you put your Python program source files.

In our example, cd C:export-kobo:

Running a Python program

A simpler alternative to using the cd command
takes advantages of the Windows file explorer.
Just navigate the file explorer to the folder
where your Python code is:

Opening a prompt from file explorer

and select the
File > Open command prompt > Open command prompt
menu:

Opening a prompt from file explorer

you will get a new Command Prompt window,
already located at the correct directory:

Opening a prompt from file explorer

Step 3: Run The Python Program

At this point, we are ready to run our program.

Type python export-kobo.py KoboReader.sqlite --list and hit Enter/Return:

Running a Python program

The Python interpreter will load our export-kobo.py program,
and run it with arguments KoboReader.sqlite and --list.

Clearly, the semantics of the arguments vary from program to program,
depending on what each program is supposed to do.

In our case, export-kobo.py will read the file
whose name is passed as the first parameter (KoboReader.sqlite)
and it will list (--list option) the titles of all the eBooks
with annotations or highlights in the database.

If we specify different command arguments, for example
python export-kobo.py KoboReader.sqlite --csv --output exported.csv,
we will get a different behavior:

Running a Python program

In particular, this second command exported all the information
contained in the KoboReader.sqlite file into
the newly created file named exported.csv in CSV format:

Running a Python program

You must check the documentation of your Python program
to know the semantics of its arguments.

Usually, if you run a Python program without arguments
you will get a synopsis of the accepted arguments:

Running without arguments shows the synopsis

If a -h or --help argument is given,
then a more verbose help message will be printed:

Running with -h shows an help message

Congratulations, now you should be able
to download and run a Python program on your own!

Acknowledgments

  • Louise Schofield nee Stokes for suggesting using the file explorer menu
    to open the command prompt at a given directory

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:YourNameProjectsPython>

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:UsersYourName> 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:Python33python

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.

Introduction

Programming has an indispensable role in our world. You would not be reading this blog without it. Behind your favorite website, like Instagram, Facebook, YouTube, there is some sort of programming at work. A bit more obvious, and just in case you didn’t know: Your cellphone has been coded.

Everything you do with your cell phone, even an old-fashioned one, responds to a series of codes written by very proficient programmers. 

Computers do not understand languages like English or Hindi. They have their own language called Machine Code, which tells them what to do, but it doesn’t make much sense to humans!

So innovative humans created an easier way of communicating with computers known as “Programming Languages.”

There are around 700 programming languages like C, C++, Java, C#, Python, PHP, Ada, etc., and studying programming fundamentals can set you apart from your equivalents, giving you a competitive edge in this technology-driven world.

Now, Suppose you plan to explore Python Programming but don’t know how to execute python code. In that case, it’s of no use, so the primary skill which you need to develop as a Python programmer is running Python scripts or code. It will be the only way of knowing if your code works as intended or not. 

Hence, this article will explain numerous ways of executing a python code depending on the platform, environment, requirements, and expertise. 

Above, you must have encountered two terms, code and scripts. Therefore, you need to know the primary differences between code and scripts before proceeding into other details.

Code Vs. Scripts

Coding Is a Genre; Scripting Is a Subgenre. It means coding is a bigger picture and includes more than just scripting. It seems confusing, right!! But the difference between them is a long debate that’s relatively hard to answer.

In simple terms, you can remember that:

blog banner 1

  • A code needs to be compiled, whereas a script is not compiled but interpreted.
  • A code file has extensions like ‘.cpp’, ‘.java’. Whereas the file containing the script has the extension ‘.py’ , ‘.php’, ‘.js’.
  • Few programming languages are C, C++, Java; on the other hand, scripting languages are Python, PHP, Javascript, and many more.

To know in-depth the variations between coding and scripting languages, you can read the Outlining The Difference Between Programming & Scripting language.

We can conclude that all scripting languages are considered programming languages, but vice-versa is not correct, and scripting languages like Python run on an interpreter.

You must be questioning, What is an Interpreter?

The Interpreter refers to system software that can read and execute the program or interpret programs. This interpretation includes the source code of the high-level language, precompiled programs and scripts. 

It should be noted that the Interpreter interprets the program line by line, i.e. translates an instruction in one go. This feature makes it easy for programmers to check a specific line while debugging, but it slows the overall execution time of the entire program.

It also does not generate any intermediate object code, which makes it more memory intensive.

However, if you can’t run Python scripts, there is no point in understanding all of this. Now let us continue to explore the method of running Python scripts.

Different Methods to Run Python Scripts:

There are the following four methods to run python scripts:

  • Using Command-Line prompt or terminal.
  • Using an IDE or Text Editor
  • Python Interactive Mode
  • Using File Manager

RUN PYTHON SCRIPT USING COMMAND LINE

The easiest way to run Python scripts is to use the command prompt. 

TO OPEN THE COMMAND PROMPT:

  • On Windows, the command line is called the command prompt or MS-DOS console. A faster way to access it is to go to “Start” → “Run” and type cmd.
  • On GNU/Linux, Multiple applications can access the command line such as xterm, Gnome terminal or console. 
  • In MAC OS X, call the system terminal through Application → Utilities → Terminal.

After successfully opening the command prompt, type the word cd followed by the path to your script file or python file and press Enter

Then write filename.py now press Enter again, and You are Done!! The screen will display the output.

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

RUN PYTHON SCRIPTS USING AN IDE OR TEXT EDITOR

While developing more significant and complex applications, it’s suggested that you should use an Integrated Development Environment (IDE) or a text editor.

IDE:

An IDE (or Integrated Development Environment) is a program committed to programming improvement. As the name infers, IDEs compose a few tools explicitly intended for software development. 

These tools usually include an editor, run, build, execution, debugging and many more.

Python’s standard distribution includes IDLE as the default IDE to write, debug, modify, and run your code and scripts. Other IDEs such as Eclipse-PyDev, PyCharm, Eric, etc., also allow you to run Python scripts inside the environment.

If you want to run a Python script from your IDE:

  • Launch PYTHON IDLE from the START MENU
  • Create a new file and write your required script.
  • Now save it (you can use  CTRL+S ) with the .py extension.

The .py extension is used on all of these files to indicate Python executable files. In Windows, pyw is another extension for Python files.

  • Finally, Run it; 

You can use the default “Run” command or fast keys like Function + F5 or just F5 to run Python scripts.

  • Bingo! Now you can see the output on your screen.

Here’s an example of running Python script on Python IDLE:

Text Editors:

The formal definition is: “A text editor is a program that edits text files”. 

Basically, a text editor is a program on your computer that allows you to create and edit files in various programming languages. 

It manages hand codes in various languages, such as HTML, CSS, JavaScript, PHP, Ruby, Python, etc. In addition, there are many text editors you can choose from, like Sublime Text Editor, Notepad++, TextWrangler(Mac Only), gedit, etc.

If you are starting with Python, you can use simple text editors like Sublime or Notepad++ or any other text editor.

You must now write a sample script. To do this:

  • Launch your preferred text editor and write your script.
  • Save the file to your desktop under the name samplefile.py or whatever you want.
  • Remember that you only need to provide the .py extension.
  • Click build in the toolbar.
  • Subsequently, the screen will display the required output according to your script.

RUN PYTHON SCRIPT USING INTERACTIVE MODE

An Interactive mode is a great way to get started with Python since it allows you to test each piece of code while you’re working on it.

  • All you have to do now is start the Python Interactive session. 
  • To do so, open a terminal or command line and type Python or Python3 depending on the Python version installed on your machine, then press Enter
  • The >>> represents the standard Interactive mode prompt on the terminal.

Note: If you don’t see these characters, your system has to be reinstalled with Python.

Below is an example of running a python script in an interactive mode:

When working with an interactive session, the statements you type are evaluated and performed immediately, though the main drawback is that the code is lost when the interactive session ends.

But, the advantage is you don’t have to wait until your code is finished to test it. Instead, you can try it out on the spot.  

So, whenever you’re working with Python and aren’t sure what a specific block of code does, just open the interactive session, paste the code, and watch what happens. 

Once you’ve completed all of your testings, you can quit interactive mode by selecting one of the following alternatives:

  • Exit() or quit() are built-in functions.
  • For Windows, use the Ctrl+Z and Enter combination.
  • Use Ctrl+D on Unix-like platforms.

RUN PYTHON SCRIPT USING FILE MANAGER

A Python script can also be started by double-clicking on its icon in the file manager.

In order to do so, you must satisfy specific requirements, which varies based on the operating system you’re using.

  • Pythonw.exe and Python.exe are related to the extensions .pyw and .py, respectively, on Windows. This facilitates the scripts to be run by just double-clicking the icon.
  • If the script has a command-line interface, a black window will appear on the screen for a second.

To prevent this, add input(‘Press Enter at Continue…’) to the script’s end, and as soon as you press Enter, the software will be terminated. 

There are certain disadvantages to this strategy.  Assume your script has a bug. Even before it reaches the statement mentioned above, the execution will be halted. 

As a result, you will be unable to view the results.

  • You need to set execution rights in the script if you are working on Unix-like systems and then run the scripts by simply double-clicking the icon in the file manager. 

Note: This method should only be used for scripts that have already been debugged and are ready to go into production because double-clicking the scripts have restrictions and rely on various things such as the file manager, operating system, file association, execution rights, etc.

Frequently Asked Questions

How do I run a .py file?

There are the following four methods to run python scripts:

1. Using Command-Line prompt.
2. Using an IDE or Text Editor
3. Python Interactive Mode
4. Using File Manager

Can you write Python in the terminal?

Yes, we can write Python scripts in the terminal.

How do I run python from the command line?

After successfully opening the command prompt, type the word cd followed by the path to your script file or python file and press Enter. Then write filename.py now press Enter again, and output will be displayed on the screen.

What is a Python terminal?

The Python interpreter (REPL) running inside a terminal window. In Windows, it is called Command Prompt. In macOS or Linux, it should be called Terminal.

Can you run Python online?

Yes, there are many online Python Interpreters like Jupyter, OnlineGDB etc.

How do I practice Python code?

At Coding Ninjas, you will get an adaptive and excelling Python Course and practice problems which will help you ease working in larger, more advanced Python environments.

Key Takeaways

Working with scripts offers its own set of benefits, including ease of learning and usage, speed of editing and execution, interactivity, and functionality. They’re also utilised to simplify complicated tasks by automating them.

Here, you gained the knowledge and skills about how to run Python in terminal using the following methods:

  • The command-line prompt
  • Your preferred integrated development environment (IDE) or text editor.
  • Using Interactive Mode
  • Using File Manager

After learning these fundamental ways, I would suggest you explore Coding Ninjas Python Course once because this provides you more ease at working in larger and more advanced Python environments, which will improve the development process and boost your efficiency.

By Aanchal Tiwari

One of the famous and trending languages nowadays is Python. One of the key skills required by a python developer is to run python scripts and codes. You’ll only be able to see if your code works as expected if you do it this way. It’s even the sole way to determine whether or not your code works at all!. To checkout how to run python script on windows follow this tutorial.

This tutorial will guide you step-by-step to run python script on windows and how to configure settings. This includes setting up the environment, platform and needs.

In this tutorial you will learn how to run python using:

  • Interactive mode of Python
  • Command Line Interface or Terminal
  • IDE or text editor of your choice
  • The file Manager by double-clicking on the python script.

Modules vs Scripts:

A script is a computer program consisting of instructions in a sequence and program. Another program executes or interprets the script.

Scripts are processed by interpreters which execute each command separately.The user users commonly call a plain text file containing Python code a script that is an informal term that indicates a top-level software file. 

Whereas, Python module is a program or code in a text file, which contains an implementation of specific functionality. This Code is used by other programs and is called a module.

So, the main difference between modules and scripts is that scripts are directly executed. Whereas, modules are imported into other programs.

Now, we will learn how to run python programs.

How to run python scripts interactively:

To run python script from windows terminal you first needs to run Windows Terminal. Go to Windows and type Command Prompt or simply use Win+X. Remember to use “Run as Administrator” option to prevent restrictions. To run python script from a .py file type the following command. If you do not know how to install python into windows, first go through the tutorial “How to Install Python on Windows” on our website.

Python example.py

Where “example.py” is a sample python script.

To type python script into terminal type Python3 and you will enter into command screen.

The >>> symbol on the terminal represents the standard interactive mode input mode. This means that user can enter the command here.

The statements you enter here executes and gives output on next line. Simply type the command and click Enter to view the output.

The above image shows the code immediately gives output after executing the code. The only disadvantage of this approach is that when you close the interactive screen, the code no longer exists.

You can leave the python interactive mode by typing exit() command or by pressing CTRL+Z key.

Running Python Script using interpreter:

Let’s say we have a python script in a sample.py file and need to run it from the command prompt. To do this, simply run the command prompt. Simply type “python sample.py” where sample.py is the name of the python script to execute. This command will execute the instructions in the sample.py file. Likewise, in this code, the instruction Hello World is displayed.

You can also output the code into some text file. To do this type python sample.py >output.txt.

The execution of python script is using Python Execution Model (PEM). It performs multiple steps to run python script.

  • Statements in scrips are executed step by step in a sequential manner by the interpreter.
  • The code is converted into bytecode which is compiled into the form of the instruction set. Bytecode is the set of instructions written in a low-level language. The high-level language is first converted into a low-level language. As computers only understand low-level instructions so they are first converted into them.
  • The interpreter finally executes the code. The Python Virtual Machine (PVM) is the final phase in the Python interpreter’s development. It is a component of the Python environment that you have installed on your computer. The PVM loads the bytecode into the Python runtime and reads and executes each action as specified. It’s the part that really executes your scripts.

Running Python script using IDE:

An Integrated Development Environment (IDE) is application software that provides the necessary tools and environment to execute a script. In Python, we have a number of IDE such as Spyder, Jupyter, Pycharm, and PyDEV.

Python IDLE is a python debugger, the compiler is a standard python compiler to run, modify and debug python modules and scripts. Moreover, standard text editors such as Sublime Text (ST), Visual Studio (VS) Code can also be linked with python to execute the code.

Running Python script from a File Manager:

You can run your python script from the file manager by double-clicking on the python script. This will mostly be done in the production stage. It is used after releasing the source code.

In windows to run a script by double-clicking you need to have your script in .py extension for python.exe and .pyw for pythow.exe. If you are using a command prompt and facing the issue of a black screen. For this, you need to and add Input(“Enter”) in the script file. This will exit the program only when you click the “Enter” button.

Congratulations, you have learned a number of techniques to run python script in Windows using:

  • Interactive mode of Python
  • Command Line Interface or Terminal
  • IDE or text editor of your choice
  • The file Manager by double-clicking on the python script.

Понравилась статья? Поделить с друзьями:
  • Windows run out of memory utorrent при создании
  • Windows run out of memory unable to allocate utorrent
  • Windows run out of memory unable to allocate 32768000 bytes
  • Windows run out of memory unable to allocate 16397 bytes
  • Windows run out of memory unable to allocate 131076 bytes