How To Run A Py Script In Linux

8 min read

Running a Python script in Linux is one of the first skills every developer, data analyst, or system administrator needs to master. Whether you are automating a repetitive task, processing large datasets, or building a web application, knowing how to run a py script in Linux efficiently can save you hours of frustration. Linux provides a powerful command-line environment that makes executing Python files straightforward, but there are several methods depending on your goals and system setup.

Prerequisites Before You Run a Python Script

Before executing any Python file, you need to confirm that Python is installed on your Linux distribution and that you have access to a terminal. Most modern Linux distributions, such as Ubuntu, Debian, Fedora, and Arch Linux, come with Python 3 preinstalled. You can verify the installation by opening your terminal and typing:

Most guides skip this. Don't And that's really what it comes down to..

python3 --version

If the command returns a version number such as Python 3.Practically speaking, 12, you are ready to proceed. 10.If you receive a “command not found” error, you will need to install Python using your distribution’s package manager That alone is useful..

sudo apt update
sudo apt install python3

You also need a Python script file with the .py extension. If you do not have one yet, create a simple test file using a text editor like nano or vim:

nano hello.py

Inside the file, add a basic line of code:

print("Hello from Linux!")

Save the file and exit the editor. Now you are ready to run it using the methods described below Nothing fancy..

Method 1: Running a Python Script with the python3 Command

The most common and straightforward way to run a py script in Linux is by invoking the Python interpreter directly from the terminal. This method does not require any special file permissions and works immediately after you create your script.

First, figure out to the directory where your script is located using the cd command:

cd /home/yourusername/scripts

Then, execute the script by calling python3 followed by the filename:

python3 hello.py

You should see the output printed directly in your terminal:

Hello from Linux!

It is important to use python3 rather than python on most modern Linux systems. Many distributions have completely removed Python 2, and the python command may either be missing or linked to an outdated version. Using python3 ensures that your script runs under the Python 3 interpreter, which is the current standard And that's really what it comes down to..

This method is ideal for quick testing, debugging, and running scripts that you do not intend to execute frequently as standalone programs.

Method 2: Making a Python Script Executable

If you want to run your Python script as if it were a native Linux command—without typing python3 every time—you can make the file executable. This approach involves two additional steps: adding a shebang line and changing the file permissions Practical, not theoretical..

Step 1: Add the Shebang Line

Open your Python script and insert the following line at the very top:

#!/usr/bin/env python3

This line is called a shebang. So it tells the Linux kernel which interpreter should be used to execute the file. Think about it: using /usr/bin/env python3 is preferred over a hardcoded path like #! /usr/bin/python3 because it searches the user’s PATH for the Python interpreter, making your script more portable across different Linux distributions.

Step 2: Change File Permissions

By default

By default, Linux files are not executable. You must explicitly grant execute permissions using the chmod command. Run the following in your terminal:

chmod +x hello.py

This command adds execute permissions for the user, group, and others. You can verify the change by listing the file details with ls -l hello.That's why py; you should now see an x in the permission string (e. g., -rwxr-xr-x).

Step 3: Run the Script Directly

Now you can execute the script by referencing its path. Because the current directory is usually not in the system PATH for security reasons, you must prefix the filename with ./:

./hello.py

The output will be identical to the previous method:

Hello from Linux!

You can now move this script to a directory in your PATH (such as ~/.local/bin or /usr/local/bin) to run it from anywhere on the system simply by typing hello.py That alone is useful..

Note: If you receive a "Permission denied" error even after running chmod, ensure the filesystem is not mounted with the noexec option, which prevents execution of binaries and scripts on that partition The details matter here..

Method 3: Running Python Modules with the -m Flag

Python’s -m switch allows you to run library modules as scripts. This is the standard way to execute tools installed via pip (like pytest, black, or http.server) and is essential for running your own packages correctly Not complicated — just consistent..

If your project structure looks like this:

my_project/
├── main.py
└── utils/
    ├── __init__.py
    └── helpers.py

You should run the entry point from the project root directory using the module path:

python3 -m my_project.main

Why use -m instead of python3 my_project/main.py? Running with -m adds the current working directory to sys.path, ensuring that relative imports and package structures resolve correctly. Running the file directly by path often breaks internal imports because Python treats the script's directory as the root package, not the project root.

This method is also how you launch built-in utilities. As an example, to serve the current directory over HTTP for quick file sharing:

python3 -m http.server 8000

Method 4: Running Scripts Inside a Virtual Environment

For any serious development, you should isolate dependencies using a virtual environment (venv). This prevents conflicts between project requirements and system packages.

Create and Activate the Environment

python3 -m venv venv
source venv/bin/activate

Your shell prompt will change (e.g., (venv) user@host:~$), indicating the environment is active. Inside this environment, the python and pip commands point to the isolated versions.

Run Your Script

With the environment active, you can use any of the previous methods, but the interpreter resolution changes:

# Method 1 style (explicit interpreter)
python hello.py

# Method 2 style (shebang respects active env)
./hello.py

# Method 3 style (module execution)
python -m my_package

Crucial Difference: Notice that inside a virtual environment, you can often use just python instead of python3. The shebang #!/usr/bin/env python3 in Method 2 will also correctly resolve to the virtual environment's interpreter because env searches the active PATH Still holds up..

To leave the environment, simply run:

deactivate

Troubleshooting Common Issues

Error Cause Solution
bash: ./usr/bin/env python3. g.On the flip side, check `mount grep noexec. py to fix line endings. Install via package manager (e.Even so, pyorsed -i 's/\r$//' hello. Consider this: '`
Permission denied Missing execute bit or filesystem mounted noexec. Run from project root using `python3 -m package.
python3: command not found Python 3 not installed. Because of that, /hello. Worth adding: Run chmod +x script. py: /usr/bin/env: bad interpreter: No such file or directory
ImportError: No module named '... , sudo apt install python3`).

Conclusion

Linux offers the flexibility to run Python scripts in whatever way best fits your workflow. For rapid iteration and debugging, invoking python3 directly (Method 1) remains the fastest feedback loop. When a script graduates to a reusable tool or CLI utility, making it executable with a shebang (Method 2) integrates it smoothly into the shell environment.

Integrating Scripts into Larger Workflows

Once a script has proven its functionality, it can be embedded into broader automation pipelines.

  • Cron jobs – Schedule periodic execution by adding a line to crontab. The script can be invoked directly with its shebang, ensuring the correct interpreter from the active environment is used:

    0 2 * * * /home/user/project/venv/bin/python /home/user/project/my_script.py >> /var/log/my_script.log 2>&1
    
  • systemd services – For long‑running or on‑demand tasks, create a unit file that activates the virtual environment before launching the program. This guarantees isolation from the system Python and provides easy status monitoring:

    [Unit]
    Description=My Python Application
    
    [Service]
    WorkingDirectory=/home/user/project
    ExecStart=/home/user/project/venv/bin/python /home/user/project/main.py
    Restart=on-failure
    
    [Install]
    WantedBy=multi-user.target
    
  • Makefiles – Use make to define common development actions (linting, testing, deployment). A typical rule might call the script with the environment already activated:

    run:
    	./venv/bin/python -m my_package
    

Packaging for Distribution

When a script evolves into a reusable library or command‑line tool, packaging it for pip simplifies installation for other developers.

  1. Project layout – Adopt a standard structure:

    my_package/
    ├─ my_package/
    │   ├─ __init__.py
    │   └─ core.py
    ├─ tests/
    ├─ pyproject.toml
    └─ README.md
    
  2. Entry points – Declare a console script in pyproject.toml (or setup.cfg) so that pip install . creates a wrapper that calls the appropriate function:

    [project.scripts]
    my-tool = "my_package.core:main"
    
  3. Build & upload – Use build to create a wheel, then publish to PyPI or a private index with twine. The resulting package can be installed on any Linux machine with a single pip install my-package, automatically pulling in the required virtual‑environment‑compatible dependencies.

Automated Testing

Reliability grows when code is exercised by a test suite The details matter here..

  • pytest – Place tests under a tests/ directory and run pytest from the project root. The virtual environment ensures that the same packages used at runtime are available for testing.
  • Coverage – Integrate pytest-cov to generate a coverage report, helping identify untested branches.
  • Continuous Integration – Services such as GitHub Actions or GitLab CI can spin up a fresh container, create
Fresh Picks

New Around Here

Readers Also Loved

Keep the Momentum

Thank you for reading about How To Run A Py Script In Linux. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home