繁体   English   中英

使用 Python 向子 shell 发送命令

[英]Using Python to send commands to a subshell

启动后,我需要向外壳程序“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>

文档

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

如果您想将输入发送到您的 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

>>> 

它会起作用@Ahmed。 在 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))  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM