Do you find yourself wanting to run Python scripts without keeping your terminal open all the time?
Or maybe you’d like your script to keep doing its thing even after you close the terminal? That’s exactly what we’ll discuss in this post.
Let’s go through this really easy way to run Python scripts in the background on Linux – I promise it’s simpler than you might think!
Making Your Python Script Executable
Before we dive into the background stuff, let’s make sure your script is ready to run on its own:
- First, add what’s called a “shebang” line at the very top of your script:
#!/usr/bin/env python3
This line tells your system which program should run this file. Using /usr/bin/env python3
is smart because it finds whatever Python version you have in your path.
It’s way better than hardcoding a specific path that might not exist on other computers!
- Next, we need to give your script permission to run:
chmod +x main.py
Think of this as giving your script its “running shoes” so it can actually do its thing!
Sending Your Script to the Background
Now for the fun part – making your script run in the background:
nohup /path/to/main.py &
The magic here is in two parts:
nohup
tells your script to ignore the “hang up” signal (so it won’t stop when you close your terminal)- The
&
at the end sends the process to the background
If you forgot to add the shebang line earlier, no worries! You can also run it like this:
nohup python /path/to/main.py &
By default, any output from your script gets saved to a file called nohup.out
. But if you want to be fancy and choose your own output file:
nohup /path/to/main.py > output.log &
Stop the Background Process
Started a script and now you need to stop it? Don’t panic! First, you need to find it:
ps ax | grep main.py
This will show you your script’s process ID (PID). Once you know that, you can stop it:
kill -9
Or if you’re feeling a bit lazy (like me most days), you can use this shortcut:
pkill -f main.py
Just be careful with pkill
– it’ll kill any process with that name, so make sure you don’t have other scripts running with the same name!
The Mystery of Missing Output
If you check your output file while the script is running and wonder, “Where’s all my print statements?”, you’re experiencing output buffering.
Python doesn’t write to the file immediately but waits until it has a bunch of text.
To fix this and see your output in real-time, use the -u
flag:
nohup python -u ./main.py &
Or with a custom output file:
nohup python -u ./main.py > output.log &
Now you can watch your script’s progress as it happens!
And there you have it – you’re now officially a Linux background-script-running wizard! This simple trick has saved me countless hours and terminals.
Next time you need to run a long process, you can set it and forget it, all while keeping your terminal free for other important stuff (like checking out more cool Python tricks!).