Ruobai Wang
Ruobai Wang

Reputation: 41

Problems with nohup of a python code which calls another nohup?

The problem is like this.

I have a python code "test.py", which calls a command line:

os.system('nohup some_command > b.txt &')
print(some_results)

and it works well, which redirects the output info of "some_command" to "b.txt", and only printing the "some_results" to the terminal.

I want to run the code in background (let it keep running when I exit the terminal), so I use this command:

nohup python test.py > a.txt &

Now everything, including the "some_results" and the output of "some_command", is redirected into "a.txt", which causes the program to run not properly.

Is there a way to redirect only the "some_results", instead of everything, to "a.txt"? What should I do?

PS: I don't know what keywords should I search, and by searching "nohup in nohup" I have not found relevant solution.

============================= Some unsuccessful attempts =========================

After reading a recommended question: Redirect stdout to a file in Python?

I had an idea:

import sys
sys.stdout=open('c.txt','w')
os.system('nohup some_command > b.txt &')
print(some_results)

But the problem is still not solved.

nohup python test.py > a.txt & redirects the python outputs to "c.txt" (as expected), but everything else to "a.txt" instead of "b.txt", and causes a failure.

python test.py > a.txt & works temporarily: It redirects the python outputs to "c.txt", the command outputs to "b.txt", and leaving "a.txt" blank, as expected (sort of).

However, the terminal would be poped up with "nohup: redirecting stderr to stdout" messages each time the "os.system" command is called. After restarting the terminal, the messages no longer pops and the program is still running, but the redirection becomes the same as nohup python test.py > a.txt &.

============== Some additional information =====================

The os.system(blabla) is executed multiple times.

The "some_command" is actually "pocketsphinx", which outputs a lot of logs including the time alignment of phonemes, and finally a line describing the phoneme sequence without time alignment. What I need is the "time alignment" section.

In normal conditions, the last line always follows the info section, no matter where they are printed.

In my problem, the last line is always in the "b.txt" correctly. The info (including the time alignments which I want them to be in "b.txt") are redirected to somewhere else.

Upvotes: 1

Views: 208

Answers (1)

hek2mgl
hek2mgl

Reputation: 157947

In your script, just redirect both stdout and stderr to a file, no nohup, no background:

os.system('some_command > b.txt 2>&1')
print(some_results)

In the terminal:

nohup python my_script.py > a.txt &

Upvotes: 1

Related Questions