Execute Python in Linux
To execute a saved Python program in Linux, open a terminal in the file’s folder and run it with the Python 3 interpreter. Most systems provide Python as python3, while some also make python point to Python 3. You can also run Python interactively, execute modules, make scripts directly executable, and pass files or options to scripts that accept them.
How Python Execution Works on Linux
Linux runs Python code through a Python interpreter. The interpreter reads either:
- A saved
.pyfile, such ashello.py - Code entered interactively at the Python prompt
- A module selected with Python’s module option
- A script launched directly through its shebang line
A Python script is a text file containing Python code. When you run it from a terminal, Python executes the file from top to bottom.
The terminal’s current directory matters. If your script is in a project folder, move into that folder before running the script so Python can find the file and so relative file paths work as expected.
How to Run a Python File From Terminal
Choose the execution method that matches what you are trying to run.
| What You Want to Run | Best Method | What You Need |
|---|---|---|
A normal saved .py file |
Run it through Python 3 | The file name and its folder |
| A quick calculation or test | Use the Python prompt | Python 3 installed |
| A package module | Run it as a module | The module available to that interpreter |
| A script as a Linux command | Make it executable | A shebang line and execute permission |
Step 1: Check Which Python Command Is Available
Open Terminal and check whether Python 3 is installed.
python3 --version
If that command is unavailable, check whether your system uses python instead.
python --version
Use the command that reports a Python 3 version. On many Linux distributions, python3 is the safer choice because it explicitly requests Python 3 rather than relying on how python is configured.
If neither command works, install Python 3 using your Linux distribution’s documented package manager, then reopen Terminal and check the version again.
Step 2: Move to the Script’s Folder
Use cd to change into the directory that contains the Python file. Replace the example path with your real project path.
cd /path/to/project
Use pwd to confirm that the terminal is in the script’s folder:
pwd
List the files in that folder and make sure the script is there.
ls
If you are creating a first script, save this code as hello.py in the current directory:
print("Hello, Linux!")
Step 3: Run the Python File
After saving hello.py, run it from that same directory:
python3 hello.py
The terminal should print:
Hello, Linux!
For a different file, replace hello.py with its actual name. If the file name contains spaces, quote it:
python3 "my script.py"
Step 4: Confirm That the Script Finished Successfully
A program can print output yet still end with an error later. After a script finishes, check its shell exit status:
echo $?
An exit status of 0 means the command completed successfully.
Pass Inputs and Options to Python Scripts
Many useful scripts need information at runtime, such as a file to analyze, an output directory, or an option that changes the calculation. Pass those values on the command line rather than editing the source file before every run.
A saved script can be reused for different inputs when its command-line arguments supply the changing values.
Python’s argparse library is designed for this. The MolSSI command-line argparse workflow supports positional inputs, named options, and automatically generated help text.
For example, a script can define a required XYZ data file plus optional bond-length settings:
import argparse
parser = argparse.ArgumentParser(description="Analyze an XYZ file.")
parser.add_argument("xyz_file", help="Path to the XYZ file")
parser.add_argument("-minimum_length", type=float, default=0)
parser.add_argument("-maximum_length", type=float, default=1.5)
args = parser.parse_args()
Ask the script which inputs it accepts before running it:
python analyze.py --help
Run the supplied analysis script with its data-file argument first and its named option after it:
python analyze.py data/water.xyz -minimum_length 1
For that analysis script, -minimum_length expects a numeric value. When you omit it, its configured default is 0. Its -maximum_length option also expects a numeric value, and its configured default is 1.5; provide that option when the script’s normal maximum is not suitable for the file you are analyzing.
A shell wildcard can pass multiple matching files when the script is written to accept more than one positional input:
python analyze_mdout.py data/*.mdout
The shell expands the wildcard into a list of matching files before Python starts. The script must be designed to accept multiple values, such as with an argparse argument configured with nargs.
Other Ways to Execute Python on Linux
Python can be executed on Linux interactively, as a module, directly through a shebang-enabled script, or by running Linux commands from Python.
Run Python Interactively
The Python REPL, or read-eval-print loop, is useful for testing expressions and short snippets without creating a file.
python3
When you see the >>> prompt, enter Python code:
print("Hello from the Python prompt")
You can also test calculations immediately:
2 + 2
Leave the interactive prompt by pressing Ctrl+D or entering:
exit()
Interactive mode is best for exploration. Put repeatable code in a .py file so it can be run, reviewed, and version-controlled later.
Run a Module With Python
Use Python’s module option when the code is installed as a module or package rather than being addressed by a file path.
python3 -m module_name
Replace module_name with the module you need to run. This is especially useful for Python-provided tools and packages because Python searches its module path using the same interpreter and environment that will run the code.
Run a Script Directly
Linux can execute a Python file like a regular program when the file starts with a shebang line and has execute permission.
Put this on the first line of the script, with no blank line before it:
#!/usr/bin/env python3
Then give the file execute permission:
chmod u+x hello.py
Run it from the current directory:
./hello.py
The env form finds python3 through your current environment. If you need to use an absolute interpreter path instead, first identify it:
command -v python3
If that command returns /usr/bin/python3, the first line can instead be:
#!/usr/bin/python3
Only use an absolute shebang path when it exactly matches the interpreter location on that Linux system.
Execute a Linux Command From Python
Yes, Python can run Linux commands. Use the subprocess module and pass the command as a list rather than building a shell command from untrusted text.
import subprocess
result = subprocess.run(
["uname", "-s"],
check=True,
text=True,
capture_output=True,
)
print(result.stdout)
This runs uname -s, captures its output, and prints it. With check=True, Python raises an error if the Linux command fails, which makes failures easier to detect in scripts and automation.
Use a Virtual Environment for Project Scripts
A virtual environment gives a project its own Python packages and helps avoid conflicts with system-wide packages or other projects.
Create one in the project directory:
python3 -m venv .venv
Activate it in Bash or Zsh:
source .venv/bin/activate
Check which Python version the active environment provides:
python --version
Run the project script while the environment is active:
python hello.py
When you are finished, leave the environment:
deactivate
If creating the environment fails, your distribution may package Python’s virtual-environment support separately. Install the applicable Python virtual-environment package through the distribution’s package manager, then create the environment again.
Fix Common Python Execution Errors
| Terminal Message or Symptom | Likely Cause | Fix |
|---|---|---|
python3: command not found |
Python 3 is not installed or is not on the shell path | Install Python 3, then reopen Terminal and check its version |
can't open file or No such file or directory |
You are in the wrong folder or typed the wrong file name | Use pwd and ls, then run the exact file name |
Permission denied with ./script.py |
The script lacks execute permission | Add execute permission and verify the shebang line |
ModuleNotFoundError |
A required package is missing from the current interpreter or virtual environment | Activate the intended environment and install the project dependency there |
SyntaxError |
The Python file contains invalid Python syntax | Read the file name and line number in the traceback, then correct that line |
| Script uses the wrong package version | The script is running under a different Python installation | Activate the correct virtual environment before running it |
A traceback is Python’s error report. Read it from the bottom upward: the final line gives the exception type and message, while the lines above show where the failure occurred.
For file-not-found errors, do not add random paths to the command. First verify the current directory and the exact spelling of the script and any input-file paths.
For missing modules, install the required dependencies before running the script again. A package installed globally may not be available inside a virtual environment, and a package installed in one virtual environment is not automatically available in another.
Confirm and Keep Python Scripts Reliable
Before relying on a command in a project, verify these execution details:
- The Python command reports Python 3.
- The terminal is in the intended project directory.
- The script file exists and has the expected name.
- The script produces its expected output.
- A script with arguments provides useful output through its help option.
- Required project dependencies are installed.
For scripts that may be imported by other Python files as well as run directly, keep executable code inside a main guard:
def main():
print("Run the program here")
if __name__ == "__main__":
main()
This prevents the main() call from running automatically when another Python file imports the script. It also makes testing and reuse easier.
Frequently Asked Questions
How do I run a .py file in Linux?
Open Terminal, change into the folder containing the file, and run it with Python 3:
python3 hello.py
Replace hello.py with your script’s real file name. If your Linux system maps python to Python 3, verify that with a version check before using python to run the file.
Can I run Python on Linux?
Yes. Linux is a common platform for Python development, scripting, automation, data analysis, and server applications. Use Python interactively with the Python 3 interpreter or save code in a .py file and execute it from Terminal.
How do I execute Python code step by step?
Use Python’s built-in debugger to pause before execution and move through the script one statement at a time:
python3 -m pdb hello.py
At the debugger prompt, use the debugger to inspect the program state and control execution through the script.
Can Python execute Linux commands?
Yes. Use Python’s subprocess module to run a command such as uname, git, or another installed program. Pass commands as a list of separate arguments instead of constructing a shell command from user input, especially when any input may be untrusted.
How can I make a Python script reusable from the terminal?
Use argparse to define positional inputs and named options, then provide a help screen with --help. Next, move the script into a project folder and run the command with representative input files before automating it.
