如何将字符串传递到 subprocess.Popen(使用 stdin 参数)?

2024-12-05 08:38:00
admin
原创
197
摘要:问题描述:如果我执行以下操作:import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one two three four fiv...

问题描述:

如果我执行以下操作:

import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one
two
three
four
five
six
')).communicate()[0]

我得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
    (p2cread, p2cwrite,
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'

显然,cStringIO.StringIO 对象与文件鸭的叫声不够接近,无法适应 subprocess.Popen。我该如何解决这个问题?


解决方案 1:

Popen.communicate()文档:

请注意,如果您想要将数据发送到进程的标准输入,则需要使用 stdin=PIPE 创建 Popen 对象。同样,要获取结果元组中除 None 之外的任何内容,您还需要提供 stdout=PIPE 和/或 stderr=PIPE。

替换 os.popen*

    pipe = os.popen(cmd, 'w', bufsize)
    # ==>
    pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin

警告使用communication()而不是stdin.write()、stdout.read()或stderr.read()来避免由于任何其他OS管道缓冲区填满并阻塞子进程而导致死锁。

因此您的示例可以写如下:

from subprocess import Popen, PIPE, STDOUT

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
grep_stdout = p.communicate(input=b'one
two
three
four
five
six
')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->

在 Python 3.5+( 为 3.6+ encoding)中,您可以使用subprocess.run将输入作为字符串传递给外部命令并在一次调用中获取其退出状态并将其输出作为字符串返回:

#!/usr/bin/env python3
from subprocess import run, PIPE

p = run(['grep', 'f'], stdout=PIPE,
        input='one
two
three
four
five
six
', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
# -> four
# -> five
# -> 

解决方案 2:

我想出了这个解决方法:

>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one
two
three
four
five
six
') #expects a bytes type object
>>> p.communicate()[0]
'four
five
'
>>> p.stdin.close()

还有更好的吗?

解决方案 3:

如果你使用的是 Python 3.4 或更高版本,那么有一个绝妙的解决方案。使用input参数而不是stdin参数,它接受一个字节参数:

output_bytes = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input=b"foo",
)

这对于check_output和有效run,但由于某种原因call或无效check_call

在 Python 3.7+ 中,你还可以添加text=Truemakecheck_output以字符串作为输入并返回字符串(而不是bytes):

output_string = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input="foo",
    text=True,
)

解决方案 4:

我有点惊讶没有人建议创建管道,在我看来这是将字符串传递给子进程的标准输入的最简单的方法:

read, write = os.pipe()
os.write(write, "stdin input here")
os.close(write)

subprocess.check_call(['your-command'], stdin=read)

解决方案 5:

我正在使用 python3,发现需要先对字符串进行编码,然后才能将其传递到 stdin:

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(input='one
two
three
four
five
six
'.encode())
print(out)

解决方案 6:

显然,cStringIO.StringIO 对象与文件鸭子的声音不够接近,无法适应 subprocess.Popen

恐怕不行。管道是低级操作系统概念,因此它绝对需要一个由操作系统级文件描述符表示的文件对象。您的解决方法是正确的。

解决方案 7:

from subprocess import Popen, PIPE
from tempfile import SpooledTemporaryFile as tempfile
f = tempfile()
f.write('one
two
three
four
five
six
')
f.seek(0)
print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()
f.close()

解决方案 8:

"""
Ex: Dialog (2-way) with a Popen()
"""

p = subprocess.Popen('Your Command Here',
                 stdout=subprocess.PIPE,
                 stderr=subprocess.STDOUT,
                 stdin=PIPE,
                 shell=True,
                 bufsize=0)
p.stdin.write('START
')
out = p.stdout.readline()
while out:
  line = out
  line = line.rstrip("
")

  if "WHATEVER1" in line:
      pr = 1
      p.stdin.write('DO 1
')
      out = p.stdout.readline()
      continue

  if "WHATEVER2" in line:
      pr = 2
      p.stdin.write('DO 2
')
      out = p.stdout.readline()
      continue
"""
..........
"""

out = p.stdout.readline()

p.wait()

解决方案 9:

在 Python 3.7+ 上执行以下操作:

my_data = "whatever you want
should match this f"
subprocess.run(["grep", "f"], text=True, input=my_data)

并且您可能想要添加capture_output=True以获取以字符串形式运行命令的输出。

在旧版本的 Python 中,替换text=Trueuniversal_newlines=True

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)

解决方案 10:

请注意,如果太大,Popen.communicate(input=s)可能会给您带来麻烦,因为显然父进程会在分叉子进程之前对其进行缓冲,这意味着此时它需要“两倍”的已用内存(至少根据“幕后”解释和此处的链接文档)。在我的特定情况下,是一个生成器,它首先完全展开,然后才写入,因此在生成子进程之前,父进程非常大,并且没有剩余内存来分叉它:s`s`stdin

`File "/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py", line 1130, in _execute_child
self.pid = os.fork()
OSError: [Errno 12] Cannot allocate memory`

解决方案 11:

这对于来说有点小题大做grep,但通过我的学习,我了解了 Linux 命令expect和 Python 库pexpect

  • 期望:与互动程序对话

  • pexpect:用于生成子应用程序、控制它们以及响应其输出中的预期模式的 Python 模块。

import pexpect
child = pexpect.spawn('grep f', timeout=10)
child.sendline('text to match')
print(child.before)

使用交互式 shell 应用程序就像使用pexpectftp一样简单

import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before   # Print the result of the ls command.
child.interact()     # Give control of the child to the user.

解决方案 12:

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
p.stdin.write('one
')
time.sleep(0.5)
p.stdin.write('two
')
time.sleep(0.5)
p.stdin.write('three
')
time.sleep(0.5)
testresult = p.communicate()[0]
time.sleep(0.5)
print(testresult)
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1950  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1439  
  在企业运营过程中,跨部门协作效率的高低直接影响着项目的推进速度与质量,进而关乎企业的整体竞争力。PLM(产品生命周期管理)项目管理软件作为一种强大的工具,正逐渐在提升跨部门协作效率方面发挥着关键作用。它打破了部门之间的信息壁垒,优化了业务流程,为企业各部门之间的协同工作提供了有力支持。PLM项目管理软件打破信息壁垒信息...
plm合规性管理   17  
  PLM(Product Lifecycle Management)软件,即产品生命周期管理软件,旨在助力企业对产品从概念设计到退役处理的全生命周期进行有效管理。通过整合产品数据、流程以及人员,PLM软件能显著提升企业的创新能力、生产效率并降低成本。然而,PLM软件的实施并非易事,众多企业在落地过程中遭遇诸多挑战。要实现...
国内plm系统排名   19  
  研发过程的可视化对于企业提升效率、保障项目顺利推进至关重要。PLM(产品生命周期管理)系统作为整合产品全生命周期信息的重要工具,与甘特图相结合,能为研发过程可视化提供强大支持。通过对PLM系统支撑下甘特图的优化展现,可以让项目团队成员、管理层等清晰了解研发进度、资源分配等关键信息,从而做出更科学的决策。接下来,我们将详...
plm系统主要干什么的   16  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用