Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script outputs to console even when it's' run in the background

I am running a python script in background, but why does it still prints to console, even when piped to a file?

I tried the following command:

python script.py &
python script.py > output.txt &

I tried with a simple script:

print "hello world"

With

python script.py &

It still prints to console.

But

python script.py > output.txt &

works as intended and does not print to console.

like image 377
extraeee Avatar asked Jan 31 '10 16:01

extraeee


People also ask

How do I run a Python script in the background terminal?

Run nohup python bgservice.py & to get the script to ignore the hangup signal and keep running. Output will be put in nohup.

How do I save the console output in Python?

Use the write() Function to Print Output to a File in Python. Use the print() Function to Print Output to a File in Python. Use sys. stdout to Print Output to a File in Python.

What happens in the background when you run a Python file?

It will directly put the output in the file you have selected.


1 Answers

Probably it is outputing on stderr. Try this:

python script.py > output.txt 2>&1 &

Alternatively it looks like you might have started a background task that is still running:

python script.py &

Type fg to bring it to the foreground, and then kill it with Ctrl-C.

like image 130
Mark Byers Avatar answered Sep 24 '22 13:09

Mark Byers