我需要向shell发送命令“MYSHELL>”在它开始之后。
prcs = subprocess.Popen("MYSHELL; cmnd1; cmnd2;",shell=True,
subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outputPrcs, err = prcs.communicate()
print outputPrcs
仅实现进入shell的问题,不发送其他命令(cmnd1; cmnd2;)。
结果: MYSHELL>
答案 0 :(得分:1)
来自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.
注意,Wait for process to terminate.
我认为您需要的是pexpect。它不在标准库中,但它会做你想要的。
示例:
import pexpect
process = pexpect.spawn("python")
process.expect_exact(">>> ")
process.sendline('print("It works")')
process.expect("\n.*\n")
response = process.after.strip()
print(response)
输出:
It works
答案 1 :(得分:0)
如果要将输入发送到shell,则应将其作为communicate
中的参数传递,如下所示:
prcs = subprocess.Popen("MYSHELL",shell=True,
subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outputPrcs, err = prcs.communicate("cmnd1; cmnd2;")
print outputPrcs
试验:
>>> 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
>>>
答案 2 :(得分:0)
它将工作@Ahmed。在Linux上尝试以下代码:
value