I've looked for similar questions, but none of which provided an answer to this issue. Apologize if I missed something.
I'm trying to redirect output of subprocess. I simply want to discard it. When I'm using the call
function of subprocess, the command works:
>>> import subprocess as sp
>>> cmd_l = ['service', 'iptables', 'restart']
>>> sp.call(cmd_l)
Redirecting to /bin/systemctl restart iptables.service
0
But when I'm using Popen
with stdout and stderr params,
>>> sp.Popen(cmd_l, stdout=None, stderr=None)
<subprocess.Popen object at 0x7fbc74a6ed90>
>>> Redirecting to /bin/systemctl restart iptables.service
The shell hangs after the command until its timedout. Also, it still prints the command output to the terminal. I thought it might be related to the stdout and stderr params, so I tried the command without them, but the outcome was the same.
The script is ran locally on the machine.
Why does this happen? How can I discard the output of the command and just keep the return code of the execution? (without using the shell=True option)
Update: I've found this answer useful for my case, and this does what I attempted to do:
with open(os.devnull, 'w') as devnull:
sp.check_call(cmd, stdout=devnull, stderr=devnull)
Also this implementation works: sp.call(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
and ignoring the PIPEs data.
But my question regards why does the Popen execution hangs until SSH session times out? is yet to be answered.
According to the docs sp.call
uses Popen
and then wait
on the proc. So why using only Popen
seems to behave different?
Edit: I'm opening a SSH connection to my linux machine, and on that machine I execute in interactive python the command. After I execute Popen, it seems to hang (I get no output, like I'm waiting for command to respond) until I get Putty error that the connection was closed. I can reconnect afterwards.