Interacting with bash from python(从 python 与 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
'
>>>
这篇关于从 python 与 bash 交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 python 与 bash 交互


- 计算测试数量的Python单元测试 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01