如何在Python 2中将字符串传递给subprocess.Popen?
发布时间:2020-12-20 12:25:11 所属栏目:Python 来源:网络整理
导读:参见英文答案 Python – How do I pass a string into subprocess.Popen (using the stdin argument)?????????????????????????????????????10个 我想使用Popen和我运行Python(2.4 / 2.5 / 2.6)的进程 我想给它一个字符串作为标准输入. 我将编写一个示例,其
参见英文答案 >
Python – How do I pass a string into subprocess.Popen (using the stdin argument)?????????????????????????????????????10个
我想使用Popen和我运行Python(2.4 / 2.5 / 2.6)的进程 我想给它一个字符串作为标准输入. 我将编写一个示例,其中进程执行“head -n 1”输入. 以下工作,但我想以更好的方式解决它,而不使用 >>> from subprocess import * >>> p1 = Popen(["echo","first linensecond line"],stdout=PIPE) >>> Popen(["head","-n","1"],stdin=p1.stdout) first line 我试图使用StringIO,但它不起作用: >>> from StringIO import StringIO >>> Popen(["head",stdin=StringIO("first linensecond line")) Traceback (most recent call last): File "<stdin>",line 1,in ? File "/usr/lib/python2.4/subprocess.py",line 533,in __init__ (p2cread,p2cwrite,File "/usr/lib/python2.4/subprocess.py",line 830,in _get_handles p2cread = stdin.fileno() AttributeError: StringIO instance has no attribute 'fileno' 我想我可以制作一个临时文件并在那里写字符串 – 但这也不是很好. 解决方法
您是否尝试将字符串作为字符串提供给
communicate?
Popen.communicate(input=my_input) 它的工作原理如下: p = subprocess.Popen(["head",stdin=subprocess.PIPE) p.communicate('firstnsecond') 输出: first 当我第一次尝试时,我忘了将stdin设置为subprocess.PIPE. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |