Search code examples
pythonsubprocessros

Python subprocess multiple non blocking communicates


I start a script with:

t = subprocess.Popen('rosrun ros_pkg ros_node', shell=True, 
                     stdout = subprocess.PIPE, 
                     stdin = subprocess.PIPE, universal_newlines=True)

I then want to communictate with that process like this:

stdout = t.communicate('new command')[0]
print(stdout)
if stdout == []:
   logic
stdout = t.communicate('new command')[0]
....

The problem is that after t.commincate the subprocess closes

There are solutions for similar problems but nothing worked for me yet please help


Solution

  • I now switched from using subprocess to using pexpect. My syntax is now as follows:

    child = pexpect.spawn('rosrun ros_pkg ros_node')
    command = child.sendline('new command')
    output = child.read_nonblocking(10000, timeout=1)
    ....
    logic
    ....
    command = child.sendline('new command')
    output = child.read_nonblocking(10000, timeout=1)
    

    Many thanks to novel_yet_trivial on reddit: https://www.reddit.com/r/learnpython/comments/2o2viz/subprocess_popen_multiple_times/