python os.popen返回的是字符串对象吗_Python-如何将字符串传递到子进程.Popen(使用stdin参数)?...

注意,如果要将数据发送到进程的stdin,则需要使用stdin=管道创建Popen对象。类似地,要在结果元组中获得除“无”之外的任何内容,还需要给stdout=管道和/或stderr=管道。

取代os.popen*pipe = os.popen(cmd, 'w', bufsize)

# ==>

pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin警告使用Communications()而不是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\ntwo\nthree\nfour\nfive\nsix\n')[0]print(grep_stdout.decode())# -> four# -> five# ->

在当前的Python 3版本中,您可以使用subprocess.run,将输入作为字符串传递给外部命令并获取其退出状态,并在一个调用中作为字符串返回其输出:#!/usr/bin/env python3from subprocess import run, PIPE

p = run(['grep', 'f'], stdout=PIPE,

input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')print(p.returncode)# -> 0print(p.stdout)# -> four# -> five# ->

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值