使用Python向subsh发送命令

2024-10-01 11:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在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>


Tags: 命令gttruestderrstdoutshellsubprocesserr
2条回答

如果要将输入发送到shell,则应将其作为communicate中的参数传递,如下所示:

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

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

测试:

^{pr2}$

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.我想你需要的是{a2}。它不在标准库中,但它可以满足您的需要。在

示例:

^{pr2}$

输出:

It works

相关问题 更多 >