0

I am new at this so hope you understand...

Now I am using python subprocess module for sending the specific command.

After I send the command1 with Popen function, I would like to send a command2 to same process one more.

Is it possible...?

// Example
// command1 -> Opening command for text program.
// command2 -> Executing the write and save command.(on above text program) 

popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
// next....?

please let me know If I understand it incorrectly.

3 Answers3

1

It is perfectly doable but you might want to look into something like pexpect which offers more control over the dialog.

cmd = subprocess.Popen(['command1'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  # no shell=True here!
stdout, stderr = cmd.communicate('command2')

This presumes that command1 will keep running and reading additional commands on its standard input.

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

Check this out. In unix, we can execute multiple commands in one go like

cmd_1;cmd_2

We will use same thing with sub-process.

Make sure to use shell=True.

import subprocess
all_cmd = "echo a;echo b;echo c"

p = subprocess.Popen(all_cmd,stdout=subprocess.PIPE, shell=True)
p_stdout,p_err = p.communicate()
print p_stdout.strip()
Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37
  • You'll generally want to avoid `shell=True` and use some other mechanism. – tripleee Dec 27 '16 at 06:46
  • @tripleee - Ya I am aware of security concern. Also , after reading comments from OP, I think my above solution won't work for him. pexpect or exscript will be useful to him. – Dinesh Pundkar Dec 27 '16 at 06:48
  • If you recommend `shell=True` you will also want to explain the caveats. See e.g. http://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess – tripleee Dec 27 '16 at 06:52
0

For catching stdout in realtime from subprocess better check catching stdout in realtime from subprocess

Hacker6914
  • 247
  • 1
  • 9