1

I create a subprocess running a python script like this:

p = subprocess.Popen(['nohup', 'python', 'listen.py'],
                     cwd="/execute",
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)

I then let the spawning thread terminate; and the spawned subprocess remains running. The user (me) is back at the bash terminal.

I wish to print to this terminal from within the subprocess (from listen.py) - how can I achieve this?

Wasif
  • 14,755
  • 3
  • 14
  • 34
Omroth
  • 883
  • 7
  • 24
  • [I think you will be able to find your solution here](https://stackoverflow.com/questions/4408377/how-can-i-get-terminal-output-in-python) – Nidhi Dave Oct 24 '20 at 09:32
  • Those are all for how to print from the spawning script - I'd like to know if it's possible to do it from the *spawned* script. – Omroth Oct 24 '20 at 10:23

2 Answers2

4

With nohup, you simply can't. One of the features of nohup is that it detaches the started process from any terminal.

Without nohup, in the trivial case, simply don't use the stdin, stdout, or stderr keyword arguments to Popen() at all; the subprocess will inherit copies of these file descriptors from the calling process.

Having a background process write to your terminal while you are using it can be extremely disruptive, though; a better solution is usually to have the process write to a log file, which you can tail -f if you want to, in a different terminal or another program if you like.

tripleee
  • 175,061
  • 34
  • 275
  • 318
1

So script A spawns script B and terminates, and then you want to access the stdout of script B?

The first thing is that you probably don't want to capture the stdout from script B in A. But the stdout has to go somewhere, such as to a file (solution 2) or it can just be inherited stdout from the parent process (solution 1).

Solution 1

The following will exit to the shell immediately then write "123" to the same terminal 3 seconds later. If you pipe script A to a file then the outputs of script B will go there too.

python -c "import subprocess; subprocess.Popen(['python', '-c', 'import time; time.sleep(3); print(123)'])"

Solution 2

If you want script A to output to the terminal, but for script B's output to be stored somewhere else then you can write it to a file directly, such as by providing the file as the stdout kwarg to Popen like so:

p = subprocess.Popen(['python', 'listen.py'],
                     cwd="/execute",
                     stdout=open('/execute/results.txt', 'w'),
                     stderr=subprocess.STDOUT)

Solution 3

Or if you specifically want to use nohup then the following will by usually default write the output from the subprocess to nohup.txt

p = subprocess.Popen(['nohup', 'python', 'listen.py'],
                     cwd="/execute",
                     stderr=subprocess.STDOUT)
Nat
  • 2,689
  • 2
  • 29
  • 35