How To Execute A Python Script In Linux : Setting Shebang And Executable Bit

A Python script in Linux requires both the interpreter and the file itself to be marked as executable before it can run. If you’re new to Linux or just starting with Python, understanding how to execute a python script in linux is a fundamental skill. This guide walks you through every step, from writing your first script to running it from the terminal.

You might think running a Python script is as simple as typing a command. In many ways, it is. But there are a few details that can trip you up, like file permissions or the shebang line. Let’s clear those up right now.

How To Execute A Python Script In Linux

Before you can run any Python script, you need to have Python installed. Most Linux distributions come with Python pre-installed. To check, open your terminal and type:

python3 --version

If you see a version number, you’re good. If not, install Python using your package manager. For Ubuntu or Debian, use:

sudo apt update && sudo apt install python3

For Fedora or CentOS, use:

sudo dnf install python3

Now, let’s create a simple Python script. Open a text editor like nano or vim:

nano hello.py

Type this inside the file:

print("Hello, Linux!")

Save the file (Ctrl+O in nano) and exit (Ctrl+X). You now have a Python script. But how do you run it?

Method 1: Using The Python Interpreter Directly

The simplest way to run a Python script is to pass it as an argument to the Python interpreter. In your terminal, type:

python3 hello.py

This tells the system to use Python 3 to interpret and run the file. You’ll see the output:

Hello, Linux!

This method works regardless of file permissions. You don’t need to make the script executable. It’s quick and perfect for testing.

But what if you want to run the script like any other command, just by typing its name? That’s where the next method comes in.

Method 2: Making The Script Executable

To run a script directly (e.g., ./hello.py), you need two things: a shebang line and executable permissions.

Step 1: Add A Shebang Line

The shebang (#!) tells the system which interpreter to use. Open your script again:

nano hello.py

Add this as the very first line:

#!/usr/bin/env python3

Your file should now look like:

#!/usr/bin/env python3
print("Hello, Linux!")

The /usr/bin/env python3 part finds the Python 3 interpreter in your system’s PATH. It’s more portable than hardcoding the path.

Step 2: Make The File Executable

Use the chmod command to add execute permissions:

chmod +x hello.py

You can verify the permissions with ls -l hello.py. You should see something like -rwxr-xr-x.

Step 3: Run The Script

Now you can run it directly:

./hello.py

You’ll see the same output. The script is now executable and can be run like any other program in the current directory.

Method 3: Running Scripts From Anywhere

If you want to run your script from any directory without typing the full path, you need to add it to your PATH. Here’s how:

  1. Move the script to a directory in your PATH, like /usr/local/bin:
sudo mv hello.py /usr/local/bin/hello

Note: I removed the .py extension for convenience. You can keep it if you prefer.

  1. Make sure it’s executable:
sudo chmod +x /usr/local/bin/hello
  1. Now run it from anywhere:
hello

This works because /usr/local/bin is typically in your PATH. You can check your PATH with echo $PATH.

Alternatively, you can add your own directory to PATH by editing ~/.bashrc or ~/.bash_profile. Add this line:

export PATH="$PATH:$HOME/scripts"

Then move your scripts to ~/scripts and reload the file with source ~/.bashrc.

Common Issues And Fixes

Even experienced users hit snags. Here are the most common problems when trying to execute a Python script in Linux.

Permission Denied

If you see Permission denied, you forgot to make the file executable. Run:

chmod +x your_script.py

Command Not Found

This usually means the script isn’t in your PATH, or you didn’t use ./ before the filename. Always use ./ for scripts in the current directory.

Bad Interpreter

If you see /usr/bin/env: ‘python3’: No such file or directory, Python 3 isn’t installed or the shebang is wrong. Check with which python3 and update the shebang accordingly.

Syntax Errors

If your script has errors, Python will tell you the line number. Double-check your code. For example, a missing parenthesis or colon can cause this.

Shebang Line Issues

Some systems have Python installed at /usr/bin/python3 instead of /usr/bin/env python3. Both work, but env is more portable. If you hardcode the path, make sure it’s correct.

Running Python Scripts With Arguments

Many scripts accept command-line arguments. For example, create a script called greet.py:

#!/usr/bin/env python3
import sys
name = sys.argv[1] if len(sys.argv) > 1 else "World"
print(f"Hello, {name}!")

Make it executable:

chmod +x greet.py

Run it with an argument:

./greet.py Alice

Output:

Hello, Alice!

You can pass multiple arguments. They are stored in sys.argv as a list.

Using Virtual Environments

When working on multiple Python projects, virtual environments help manage dependencies. Here’s how to create and use one:

  1. Install virtualenv if you don’t have it:
pip3 install virtualenv
  1. Create a virtual environment:
python3 -m venv myenv
  1. Activate it:
source myenv/bin/activate

Your prompt will change to show the environment name. Now, when you run your script, it uses the Python interpreter and packages from this environment.

  1. To deactivate, simply type:
deactivate

Virtual environments are especially usefull when you need different versions of libraries for different projects.

Running Scripts In The Background

Sometimes you want a script to keep running even after you close the terminal. Use the & symbol:

python3 long_script.py &

This runs the script in the background. You can bring it to the foreground with fg or kill it with kill %1 (if it’s job number 1).

For scripts that should run even after logout, use nohup:

nohup python3 long_script.py &

Output will be saved to nohup.out by default.

Debugging Python Scripts

When your script doesn’t work as expected, you can debug it in several ways:

  • Add print statements to see variable values.
  • Use Python’s built-in debugger: python3 -m pdb your_script.py
  • Check for syntax errors with python3 -m py_compile your_script.py
  • Use python3 -B your_script.py to avoid creating .pyc files.

For example, to step through your code with pdb:

python3 -m pdb hello.py

Then use commands like n (next), c (continue), or q (quit).

Automating Script Execution

You can schedule Python scripts to run at specific times using cron. Edit your crontab:

crontab -e

Add a line like this to run a script every day at 6 AM:

0 6 * * * /usr/bin/python3 /home/username/scripts/daily_report.py

Make sure the path to Python and the script are absolute. Cron runs with a limited environment, so test your script first.

Scripts With GUI Or Web Interfaces

If your Python script uses a graphical interface (like Tkinter) or a web framework (like Flask), you run it the same way. For example:

python3 app.py

For web apps, you might need to run them on a specific port or bind to an IP address. Check your script’s documentation.

Security Considerations

When you make a script executable, anyone who can run it can execute it. Be careful with scripts that have sensitive data or run with elevated privileges. Always review scripts from untrusted sources before running them.

Also, avoid running scripts with sudo unless absolutely necessary. If you must, ensure the script is secure and doesn’t have any malicious code.

Using Shebang With Different Python Versions

If you have multiple Python versions installed, you can specify which one to use in the shebang:

#!/usr/bin/env python3.8

Or for Python 2 (though it’s deprecated):

#!/usr/bin/env python2

You can also use #!/usr/bin/python3 directly if you know the exact path. But env is more flexible.

Running Scripts From A Different Directory

If your script is in /home/user/projects/ and you’re in /tmp, you can run it with:

python3 /home/user/projects/script.py

Or if it’s executable:

/home/user/projects/script.py

You can also change to the script’s directory first:

cd /home/user/projects && ./script.py

Using Aliases For Quick Execution

If you run a script often, create an alias in your shell configuration file (~/.bashrc or ~/.zshrc):

alias myapp='python3 /path/to/script.py'

Then reload with source ~/.bashrc. Now you can run myapp from anywhere.

Scripts That Need Root Privileges

Some scripts require root access to modify system files or install packages. Run them with sudo:

sudo python3 script.py

But be cautious. Only use sudo if you trust the script and understand what it does.

Handling Script Output

You can redirect output to a file:

python3 script.py > output.txt

Or append to a file:

python3 script.py >> output.txt

To see errors as well, use:

python3 script.py &> output.txt

This captures both stdout and stderr.

Using The Python Interactive Shell

If you just want to test a few lines of code, you don’t need a script. Type python3 in the terminal to enter the interactive shell. You can run Python commands line by line. Exit with exit() or Ctrl+D.

Common Pitfalls For Beginners

  • Forgetting the shebang line when making a script executable.
  • Using python instead of python3 on systems where Python 2 is the default.
  • Not using ./ before the script name when in the current directory.
  • Editing scripts with Windows line endings (CRLF) instead of Unix line endings (LF). This can cause shebang errors.
  • Running scripts with spaces in the filename without quoting or escaping.

To fix line ending issues, use dos2unix on your script:

dos2unix script.py

Performance Tips

For scripts that run frequently, consider compiling them to bytecode. Python does this automatically when you import modules, but you can also do it manually:

python3 -m compileall script.py

This creates a __pycache__ directory with compiled files. It speeds up loading but not execution.

Also, avoid using #!/usr/bin/env python3 in scripts that need to start quickly, because env adds a tiny overhead. For most cases, it’s negligible.

Conclusion

Now you know multiple ways to execute a Python script in Linux. Whether you use the interpreter directly, make the file executable, or add it to your PATH, the process is straightforward. Start with the simple method (python3 script.py) and graduate to executable scripts as you get comfortable.

Remember to check permissions, use the correct shebang, and test your scripts in a safe environment. With these skills, you can automate tasks, build applications, and explore the full power of Python on Linux.

Frequently Asked Questions

How Do I Run A Python Script In Linux Without Making It Executable?

Simply type python3 script.py in the terminal. You don’t need to change permissions. This works for any Python script.

What Is The Shebang Line And Why Do I Need It?

The shebang line (#!/usr/bin/env python3) tells the system which interpreter to use when you run the script directly. Without it, the system doesn’t know it’s a Python script.

Can I Run A Python Script From Any Directory?

Yes, if you provide the full path or if the script is in a directory listed in your PATH environment variable. Otherwise, you need to be in the same directory or use ./.

Why Do I Get “Permission Denied” When Trying To Run My Script?

You need to make the file executable with chmod +x script.py. This adds the execute permission for the owner, group, and others