这当然是在其他地方关于子流程的长期讨论的一部分。但答案很简单,应该打破。
如果我使用 Python 3 的 subprocess.run(),如何将字符串“foo”传递给在 stdin 上期望它的程序?
当args参数作为序列给出时,我遇到了subprocess.Popen的问题.
例如:
import subprocess
maildir = "/home/support/Maildir"
Run Code Online (Sandbox Code Playgroud)
这工作(它打印正确的/ home/support/Maildir目录大小):
size = subprocess.Popen(["du -s -b " + maildir], shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
print size
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用(尝试):
size = subprocess.Popen(["du", "-s -b", maildir], shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
print size
Run Code Online (Sandbox Code Playgroud)
怎么了?
我的python代码生成子进程,它打印出stdout和stderr的消息.我需要以不同的方式打印它们.
我有以下代码来生成子进程并从中获取stdout结果.
cmd = ["vsmake.exe", "-f"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, ''):
print line,
sys.stdout.flush()
pass
p.wait()
Run Code Online (Sandbox Code Playgroud)
如何修改代码以检查子进程是否也通过stderr打印出消息?
一旦子进程打印出来,我需要打印出stderr和stdout.它是跨平台实现,因此它应该在Mac/Linux/PC上运行.
我想运行一些命令并抓取输出到stderr的任何内容.我有两个版本的功能,执行此版本1.
def Getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import sys
mswindows = (sys.platform == "win32")
import os
if not mswindows:
cmd = '{ ' + cmd + '; }'
pipe = os.popen(cmd + ' 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts = 0
if text[-1:] == '\n': text = text[:-1]
return sts, text
Run Code Online (Sandbox Code Playgroud)
和版本2
def Getstatusoutput2(cmd):
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()
return return_code, proc.stdout.read(), proc.stderr.read()
Run Code Online (Sandbox Code Playgroud)
第一个版本按照我的预期打印stderr输出.第二个版本在每行后打印一个空行.我怀疑这是由于版本1中的文本[-1:]行...但我似乎无法在第二版中做类似的事情.任何人都可以解释我需要做什么才能使第二个函数生成与第一个函数相同的输出而在它们之间没有额外的行(并且在最后)?
更新:这是我打印输出的方式这就是我打印的方式 …
我有一个 python 脚本,需要在其中调用 shell 命令。shell 命令可以接受来自文件或标准输入的输入。
在我的脚本中,输入存储在变量中。调用命令的正确方法是什么?如果重要的话,shell 命令不会产生任何输出。
我知道我可以将变量的内容写入文件并使用该文件作为参数调用命令,但这似乎不优雅。当然,还有更好的方法。
有人能告诉我那是什么吗?谢谢。
我想用Python运行一个进程(2.4/2.5/2.6)Popen,我想给它一个字符串作为它的标准输入.
我将编写一个示例,其中进程执行"head -n 1"输入.
以下工作,但我想以更好的方式解决它,而不使用
echo:
>>> from subprocess import *
>>> p1 = Popen(["echo", "first line\nsecond line"], stdout=PIPE)
>>> Popen(["head", "-n", "1"], stdin=p1.stdout)
first line
Run Code Online (Sandbox Code Playgroud)
我尝试使用StringIO,但它不起作用:
>>> from StringIO import StringIO
>>> Popen(["head", "-n", "1"], stdin=StringIO("first line\nsecond 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'
Run Code Online (Sandbox Code Playgroud)
我想我可以制作一个临时文件并在那里写字符串 …
我试图将一个文件传递给一个程序(MolPro),我用Python开始作为子进程.
它通常将文件作为参数,在控制台中如下所示:
path/molpro filename.ext
Run Code Online (Sandbox Code Playgroud)
其中filename.ex包含要执行的代码.或者一个bash脚本(我在Python中尝试做的):
#!/usr/bin/env bash
path/molpro << EOF
# MolPro code
EOF
Run Code Online (Sandbox Code Playgroud)
我正在尝试在Python中执行上述操作.我试过这个:
from subprocess import Popen, STDOUT, PIPE
DEVNULL = open('/dev/null', 'w') # I'm using Python 2 so I can't use subprocess.DEVNULL
StdinCommand = '''
MolPro code
'''
# Method 1 (stdout will be a file)
Popen(['path/molpro', StdinCommand], shell = False, stdout = None, stderr = STDOUT, stdin = DEVNULL)
# ERROR: more than 1 input file not allowed
# Method 2
p = Popen(['path/molpro', StdinCommand], shell …Run Code Online (Sandbox Code Playgroud) 我正试图在奴隶模式下运行它时通过管道向mplayer发送命令,如下所示:
import subprocess, time
# start mplayer
song = 'mysong.mp3'
cmd = ['mplayer', '-slave', '-quiet', song]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
# send a command every 3 seconds.
# Full command reference here: http://www.mplayerhq.hu/DOCS/tech/slave.txt
while True:
print('sleep 3 seconds ...')
time.sleep(3)
cmd = 'get_meta_artist'
print('send command: {}'.format(cmd))
p.stdin.write(cmd)
output = p.communicate()[0]
print(output)
Run Code Online (Sandbox Code Playgroud)
但输出没什么.
我从这个问题中拿了例子.
在终端中运行相同的mplayer命令工作正常.我在这里错过了什么?
更新:
我将cmd从"get_meta_artist"更改为"get_meta_artist \n",以便将换行符发送到管道,但输出中仍然没有任何内容.
UPDATE2:
我将cmd更改为"\npause \n",音乐暂停了.这意味着通过stdin发送命令工作.这意味着"\nget_meta_artist \n"命令的输出字符串未按预期传送回来....
我有一个逐行读取文本的脚本,稍微修改一行,然后将该行输出到一个文件.我可以将文本读入文件中,问题是我无法输出文本.这是我的代码.
cat = subprocess.Popen(["hadoop", "fs", "-cat", "/user/test/myfile.txt"], stdout=subprocess.PIPE)
for line in cat.stdout:
line = line+"Blah";
subprocess.Popen(["hadoop", "fs", "-put", "/user/test/moddedfile.txt"], stdin=line)
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误.
AttributeError: 'str' object has no attribute 'fileno'
cat: Unable to write to output stream.
Run Code Online (Sandbox Code Playgroud) 在开发一个 python 项目时,我需要将字符串复制到剪贴板,以便用户根据输入在其他应用程序上使用。现在我有以下内容:
os.system(f"echo {phrase}| clip")
Run Code Online (Sandbox Code Playgroud)
目前它在 python 控制台中运行良好,但每当我执行 ctrl+v/右键单击+粘贴功能时,它都会粘贴 {phrase},但还会在其正下方包含一个新行,这会导致其他应用程序失效。
我尝试过在 {phrase} 上使用 str.strip() 和 str.rstrip() 但没有什么区别。任何帮助,将不胜感激。
我只想在我的覆盆子pi上建立一个小蟒蛇音乐客户端.我安装了"mpg321",它运行良好,但现在我的问题.发送命令后
os.system("mpg321 -R testPlayer")
Run Code Online (Sandbox Code Playgroud)
python等待播放,暂停或退出等用户输入.如果我在终端中写这个,播放器暂停音乐或退出.完美,但我希望python这样做,所以我发送命令
os.system("LOAD test.mp3")
Run Code Online (Sandbox Code Playgroud)
其中LOAD是加载此mp3的命令.但没有任何反应.当我通过终端退出播放器时,我收到错误消息:
sh: 1: LOAD: not found
Run Code Online (Sandbox Code Playgroud)
我认为这意味着
os.system("mpg321 -R testPlayer")
Run Code Online (Sandbox Code Playgroud)
采取整个过程,在我退出之后,python尝试执行comman LOAD.那么我如何让这些东西一起工作呢?
我的代码:
import os
class PyMusic:
def __init__(self):
print "initial stuff later"
def playFile(self, fileName, directory = ""):
os.system("mpg321 -R testPlayer")
os.system("LOAD test.mp3")
if __name__ == "__main__":
pymusic = PyMusic()
pymusic.playFile("test.mp3")
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!