从 python 与 bash 交互

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)