从 python 与 bash 交互

2022-01-18 00:00:00 python subprocess bash

问题描述

我一直在玩 Python 的 subprocess 模块,我想用 python 中的 bash 做一个交互式会话".我希望能够像在终端仿真器上一样从 Python 读取 bash 输出/写入命令.我想一个代码示例可以更好地解释它:

I've been playing around with Python's subprocess module and I wanted to do an "interactive session" with bash from python. I want to be able to read bash output/write commands from Python just like I do on a terminal emulator. I guess a code example explains it better:

>>> proc = subprocess.Popen(['/bin/bash'])
>>> proc.communicate()
('user@machine:~/','')
>>> proc.communicate('ls
')
('file1 file2 file3','')

(显然,它不是那样工作的.)这样的事情可能吗?如何?

(obviously, it doesn't work that way.) Is something like this possible, and how?

非常感谢


解决方案

试试这个例子:

import subprocess

proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = proc.communicate('ls -lash')

print stdout

您必须阅读有关 stdin、stdout 和 stderr 的更多信息.这看起来不错:http://www.doughellmann.com/PyMOTW/subprocess/

You have to read more about stdin, stdout and stderr. This looks like good lecture: http://www.doughellmann.com/PyMOTW/subprocess/

另一个例子:

>>> process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> process.stdin.write('echo it works!
')
>>> process.stdout.readline()
'it works!
'
>>> process.stdin.write('date
')
>>> process.stdout.readline()
'wto, 13 mar 2012, 17:25:35 CET
'
>>> 

相关文章