python控制台输入字符串作为参数_Python-如何将字符串传递到subprocess.Popen(使用stdin参数)?...
小編典典
Popen.communicate() 說明文件:
請注意,如果要將數據發送到進程的stdin,則需要使用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\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->
在當前的Python 3版本中,你可以使用subprocess.run,將輸入作為字符串傳遞給外部命令并獲取其退出狀態,并在一次調用中將輸出作為字符串返回:
#!/usr/bin/env python3
from subprocess import run, PIPE
p = run(['grep', 'f'], stdout=PIPE,
input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
# -> four
# -> five
# ->
2020-02-12
總結
以上是生活随笔為你收集整理的python控制台输入字符串作为参数_Python-如何将字符串传递到subprocess.Popen(使用stdin参数)?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 惠达马桶6151价格A和w表示什么?
- 下一篇: 厕所的墙上爬了一些小螺丝是怎么回事?