0

I need to send commands to shell "MYSHELL>" after it has been initiated.

prcs = subprocess.Popen("MYSHELL; cmnd1; cmnd2;",shell=True,
subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

outputPrcs, err =  prcs.communicate()
print outputPrcs

Problem only entering shell is implemented, Other commands (cmnd1; cmnd2;)aren't sent.

Result: MYSHELL>

3
  • Probably because MYSHELL is still executing. What your command means is "Start MYSHELL, wait for it to finish, and then do cmnd1 and cmnd2" Commented Feb 9, 2016 at 12:04
  • What do you want to achieve? Do you want to send "cmnd1" and "cmnd2" to your shell as input, or do you want to execute other programs? Commented Feb 9, 2016 at 12:08
  • I want to send cmnd1 cmnd2 to MYSHELL as input in that shell Commented Feb 9, 2016 at 13:53

3 Answers 3

1

From the docs:

communicate(self, input=None)
   Interact with process: Send data to stdin.  Read data from
   stdout and stderr, until end-of-file is reached.  Wait for
   process to terminate.  The optional input argument should be a
   string to be sent to the child process, or None, if no data
   should be sent to the child.

Notice, Wait for process to terminate. I think what you need is pexpect. It isn't in the standard library, but it'll do what you want.

Example:

import pexpect

process = pexpect.spawn("python")
process.expect_exact(">>> ")
process.sendline('print("It works")')
process.expect("\n.*\n")
response = process.after.strip()
print(response)

Output:

It works
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to send input to your shell then you should pass it as an argument in communicate, like so:

prcs = subprocess.Popen("MYSHELL",shell=True,
subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

outputPrcs, err =  prcs.communicate("cmnd1; cmnd2;")
print outputPrcs

test:

>>> from subprocess import *
>>> p = Popen("python", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
>>> o,e = p.communicate("print 'it works'")
>>> print o
it works

>>> 

1 Comment

I tried code above, it works. Instead of python.I used bash and a echo it works. But, still doesn't work with MYSHELL>
0

It will work @Ahmed. Try below code on linux:

from subprocess import *  
cmd = "MYSHELL\ncmd1\ncmd2\n"
p = Popen('/bin/bash', shell=False, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)    
o, e = p.communicate(cmd)    

print('Output: ' + o.decode('ascii'))  
print('Error: '  + e.decode('ascii'))  
print('code: ' + str(p.returncode))  

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.