Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing to file python script running as a background process

I have a python script that takes about 3 hours to run. I want to print some of the data it generates to a .csv file.

I'm on centos and I'm running my script like so:

python my_script.py > output.csv &

I also tried:

python my_script.py &> output.csv 

Nothing prints to output.csv, not even some test statements right at the beginning of the script.

The next thing I tried was opening a file in my script - f = open('output.csv', 'a') and writing to it using f.write(). Again, nothing shows up in the file (although it does get created).

How can I create my output.csv with the data that I want? It seems to work normally when it's not a background process but I'd like it to run in the background.

I'm printing just like so:

print('hello, this is a test')

and in another version, I have something like this:

f = open('output.csv', 'a')
f.write('hello, this is a test')

I get exactly the same result in both cases. The file gets created, but nothing is actually written to it.

Any help is appreciated. Thank you!

like image 870
ellen Avatar asked Dec 09 '18 02:12

ellen


People also ask

How do I stop a python script from running in the background?

# Simple script to start / stop a python script in the background. # To Use: # Just run: "./startstop.sh". If the process is running it will stop it or it will start it if not.

How do I know if python script is running in the background?

I usually use ps -fA | grep python to see what processes are running. The CMD will show you what python scripts you have running, although it won't give you the directory of the script. Save this answer.

How do I run a python process in the background?

import os pid = os. fork() if pid == 0: Continue to other code ... This will make the python process run in background. Save this answer.

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

Try flushing the stdout buffer:

Python >= 3.3:

print('hello, this is a test', flush=True)

Earlier versions:

import sys

print('hello, this is a test')
sys.stdout.flush()
like image 101
cody Avatar answered Sep 25 '22 02:09

cody