10

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.

JBaczuk
  • 13,886
  • 10
  • 58
  • 86
extraeee
  • 3,096
  • 5
  • 27
  • 28
  • This should just work. Is `print "something"` the exact statement you're using? – Thomas Jan 31 '10 at 16:14
  • Can you post the exact full source of the program you have? (assuming it's not too much) – Mark Byers Jan 31 '10 at 16:21
  • it's doing a lot of stuff, but basically i'm just using the python print command for outputting results – extraeee Jan 31 '10 at 16:40
  • Could you try first with a very simple program that just prints "hello world"? If that doesn't work then post that code here. If that does work, the problem is in your script, not with how you are calling it. – Mark Byers Jan 31 '10 at 18:50
  • If your original `script.py` is just outputing using `print` then it should behave in the same way as your simplified `script.py`. So if they are behaving differently, it seems quite likely that your original `script.py` is not just using print, but also outputing text using other methods. Perhaps you need to take a look at the code and see how exactly it is output text and maybe that will provide hints. – Mark Byers Feb 01 '10 at 00:15

5 Answers5

9

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
4

The problem with python here is that it would buffer stdout and won't drop it to disk. You need to run your script like that

python -u script.py > output.txt &

Or you can use unbuffered output (unbuffered stdout in python (as in python -u) from within the program)

Community
  • 1
  • 1
Alexey Smirnov
  • 2,573
  • 14
  • 20
2

Should that have been

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

See this for a clarification on the usage of 2>&1

t0mm13b
  • 34,087
  • 8
  • 78
  • 110
2

Even this is not enough sometimes. Some applications write to /dev/console instead of /dev/stdout or /dev/stderr. Applications that prompt for a password often do this.

dj_segfault
  • 11,957
  • 4
  • 29
  • 37
1

Do you print to standard output or standard error? those are two different streams.

Program 2> file # pipe standard error
Program 2>&1 # pipe standard error to standard output (join streams)
Program > file 2>&1 # pipe both channels to file
Anycorn
  • 50,217
  • 42
  • 167
  • 261