How to run a Python script

by Alex
How to run a Python script

Every Python developer must know how to run scripts because it is the only way to check that the code he has written works. To run a script, the programmer can use:

  • Command line (terminal).
  • Interactive Python mode.
  • A text editor or full-featured IDE.
  • Operating System File Manager (run through the GUI).

Each method has its own peculiarities, so its choice depends not only on preference or habits, but also on the extent to which the programmer wants to control the parameters of running the script.

Scripts and modules should not be confused, although the differences between them are not great. Scripts are files with executable code, while modules are files whose code is imported into scripts, in other words, libraries.

The interpreter and its installation

An interpreter is software that allows you to run Python scripts. Technically speaking, the interpreter is the linking layer between the Python code and the machine code. The interpreter is used every time a programmer runs code: interactively, through the command line, always.

It’s not hard to install the interpreter on Windows, just find Python in the Microsoft Store and install it.

But if you have an older version of Windows and the previous version doesn’t work, you have to go to the official Python website, download and run the installation file and follow the installation instructions. Don’t forget to check the box for Python to be added to the Windows PATH when installing. On Linux, you usually don’t need to install anything because Python is included in its distribution.

Running Python code interactively

Programmers often use interactive session mode to work with small pieces of code. In this mode, the entered Python code is interpreted and executed immediately. That is, you don’t need to create a file and run it. To enter interactive mode in Windows, you can use one of several methods:

  • From the start menu, run the “cmd” command line. Then run the command “python” there. After that the version of the interpreter, date, time and other information should appear. A few “>” symbols should also appear to show that you can type commands.
  • Press <Win>+<R>, the “Run” window will appear. Type “python”. A command line with an interactive session running should open. It should also display version, date and time information, as well as “>” symbols.
  • The interactive session feature is also built into IDLE. It can be started from the start menu by searching for “IDLE” and clicking on the icon found. This will immediately open an online session. The advantage of using IDLE is the syntax highlighting.

To start an interactive session in Linux, you have to run the command “python3” or “python2” in the terminal. The key combinations used to exit interactive mode are: <Ctrl>+<Z> and then press <Enter>. Or you can just type quit() or exit() at the command line.

Working in interactive mode in IDLE is possible not only in Windows, but also in Linux. There is no point in it, because the Linux terminal is quite handy and provides all the necessary tools, unlike the Windows command line.

Examples of work in an interactive session

An interactive session is an essential and important tool. With it the programmer can quickly check the code he is not sure about. The code is executed immediately after input, but this does not mean that only one-line operations can be used in the terminal, for example:

>>> a = 2
>>> b = 3
>>> a + b
5
>>> 2 + 3
5
>>> quit()
Note that you don’t need to use print() to print the result of an expression to the terminal in an interactive session.

You can also write functions, loops, and conditions on the command line. In addition, you can import modules in an interactive session. The command line automatically determines when to write a multi-line instruction; for example, if the programmer wants to declare a function, he writes:

>>> def a():
...     for x in range(5):
...         print(x, end = " ")
...
>>>

“>>>>” is simply a character displayed on the command line, indicating that input is possible. The ellipses indicate that the input is not complete, thus allowing the programmer to write complex constructions of several lines.

Don’t forget to enter the desired number of spaces after the “…” is displayed! To exit this mode, press another .

The next command calls the function we just created:

>>> a()
0 1 2 3 4 >>>

The input indicators stayed on the same line because we set the print function to divide with the argument end = " ".

Running a Python script on the command line

The interactive session allows you to test the code, but as soon as it finishes, all the code is lost. Therefore, most of the code is written using text files that have the “.py” extension. They can be created with any text editor, even regular notepad will do. Suppose our script prints “Hello World!”, so the code will be as follows:

print("Hello World!")

Let’s write it in the file world.py. There are several ways to run it from the command line.

The command “python” and run by name

The easiest and most practical way to run scripts is to use the “python” command. You need to open the command line and write “python script_name”. It is important that the script is either in the directory from which you run the command line or in the directory specified in the PATH environment variable. Then the launch will be successful:

D:python>python world.py
Hello World!

If you have two versions of Python installed on your computer (which is usually the case on Linux) you should use the commands “python3” and “python2” to call the appropriate version. In recent versions of Windows, you can run a Python script simply by entering its name:

D:python>world.py

This will start a new console, display a message in it and close. We won’t see anything. To avoid this, you can add input() to the end of the file so that the script waits for user input. This is possible because Windows automatically determines which program (in this case, the Python interpreter) to use to start the file. On Linux you can also use this method, but at the beginning of the Python script the full path to the interpreter must be specified on the first line:

#!/usr/bin/python3

or

#!/usr/bin/env python3

After that you need to allow the file to run (make it executable).

chmod u+x world.py

Now just run the script by typing its name in the terminal and adding “./” before it:

./world.py
Hello World!

Running a module

Sometimes it may be necessary to run a module as a script. The usual way, however, gives a warning on the command line that the file can’t be opened. To run a module as an executable, you need to use the command:

D:python>python -m world.py
Hello World!

Redirecting the output

If you want to save the output of a script somewhere so you can use it in a future operation, you can redirect the output from the console to, for example, a file. The “>” operator is used for this purpose. Let’s revert the contents of our world.py file back to its original version:

print("Hello World!")

Now let’s run it. The full command looks like this:

D:python>python world.py > output.txt

Here output.txt is the text file where the result of the script execution is written. The operation can be used both on Windows operating system and Unix-like systems. If the file where the result is to be written doesn’t exist, the system will create it automatically. When you use the “>” operator, the contents of the file into which the data is to be output are completely overwritten. If existing data is to be saved, the “>>” operator is used. For example, we already have an output.txt file with a greeting line (after creating it with the previous command). Now let’s add one more line to it:

D:python>python world.py >> output.txt

You can run this script several times and the whole hello file will be appended with new strings.

Using IDLE

IDLE is the official integrated development environment that comes with the Python interpreter. It allows you to work interactively and write and run scripts. In addition, IDLE supports syntax highlighting and debugging. Working in interactive mode is not unlike what has been described for the Windows command line and the Linux terminal. The programmer writes code that is immediately executed by the interpreter.

Running the script

In order to run a script in IDLE you first need to open it with “File – Open” or with the <Ctrl>+<O> keys. Then it must be run with “Run – Run Module” or with the <F5> key.

Running the scriptWhen you run the script you can specify custom parameters, for this use “Run – Run… Customized” or key combination <Shift>+<F5>. In the “Command Line Arguments for sys.argv” field you should write necessary arguments.

Running the script from the interactive mode

Sometimes you may need to check the code of a script when working in the interactive mode. You don’t need to use a terminal or open the script in IDLE, you can run it directly from an interactive session using different methods.

import

When you import a module into a script, all the code it contains is executed. If the module contains only declarations of functions and classes and assignment of values, the programmer will not see anything. But if the module outputs something on the screen, works with files, it will show up on import. Thus it is possible to import the module interactively to see the results of its execution, but you can only do it once, because nothing will happen during the next imports within the same session, because with each new import the interpreter refers to a module written in cache and not to a real file.

importHere I imported the sys library in order to put the full path to my module in the path. You can see that the greeting is only displayed after the first attempt to import my module.

exec()

The exec() statement first reads the contents of the module, then sends it to the function that executes the code. The syntax looks like this:

>>> exec(open('D:pythonworld.py').read())

Running scripts from a text editor or IDE

If the programmer is working on a large project, the standard IDLE and notepad are not enough. In this case, either a text editor or a full-fledged IDE is used. Most text editors have developed plugins which allow you to run Python scripts with a single mouse click. The VS Code text editor is very popular right now. Here you can find a description of how to use it. Most IDEs support scripting by default. This is usually done using the “Run/Debug button” built into the toolbar. IDEs such as Eclipse, PyCharm, Eric, NetBeans, and others support this feature.

Running scripts with a file manager

In any operating system with a graphical interface, you can run a Python script by double-clicking on a file. However, this has its own nuances, firstly, the system must associate the “.py” extension with the Python interpreter, and secondly, this method limits the programmer, not allowing to specify additional parameters. This method can be used not only in Windows, but also in Unix-like systems. However, after starting, the console window will immediately close. To solve this problem, the input() operator is added to the end of the script, so the console won’t close until it receives input from the user. Another problem is the inability to detect and debug errors. Even if the programmer adds input(), the console will close if an error occurs while the script is running. This is the most unreliable method, which imposes a lot of restrictions on the programmer. It is better to give up the idea of using the file manager while debugging scripts and go back to the standard command line launching methods.

Related Posts

LEAVE A COMMENT