我用subprocess模块调用不同的进程.但是,我有一个问题.
在以下代码中:
callProcess = subprocess.Popen(['ls', '-l'], shell=True)
Run Code Online (Sandbox Code Playgroud)
和
callProcess = subprocess.Popen(['ls', '-l']) # without shell
Run Code Online (Sandbox Code Playgroud)
两者都有效.阅读文档后,我开始知道这shell=True意味着通过shell执行代码.这意味着在缺席的情况下,该过程将直接启动.
那么我应该更喜欢我的情况 - 我需要运行一个进程并获得其输出.从shell内部或外部调用它有什么好处.
我的python脚本使用subprocess来调用非常嘈杂的linux实用程序.我想将所有输出存储到日志文件中并向用户显示一些输出.我认为以下内容可行,但在实用程序产生大量输出之前,输出不会显示在我的应用程序中.
#fake_utility.py, just generates lots of output over time
import time
i = 0
while True:
print hex(i)*512
i += 1
time.sleep(0.5)
#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
for line in proc.stdout:
#the real code does filtering here
print "test:", line.rstrip()
Run Code Online (Sandbox Code Playgroud)
我真正想要的行为是过滤器脚本在从子进程接收时打印每一行.Sorta就像tee使用python代码一样.
我错过了什么?这甚至可能吗?
更新:
如果将a sys.stdout.flush()添加到fake_utility.py,则代码在python 3.1中具有所需的行为.我正在使用python 2.6.您会认为使用proc.stdout.xreadlines()将与py3k一样工作,但事实并非如此.
更新2:
这是最小的工作代码.
#fake_utility.py, just generates lots of output over time
import sys, time
for i in range(10):
print i
sys.stdout.flush()
time.sleep(0.5)
#display out put line by …Run Code Online (Sandbox Code Playgroud) 我想subprocess.check_output()用ps -A | grep 'process_name'.我尝试了各种解决方案,但到目前为止没有任 有人可以指导我怎么做吗?
要从我的Python脚本启动程序,我使用以下方法:
def execute(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = process.communicate()[0]
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise ProcessException(command, exitCode, output)
Run Code Online (Sandbox Code Playgroud)
因此,当我启动一个类似的过程时Process.execute("mvn clean install"),我的程序会一直等到过程结束,然后我才能获得程序的完整输出.如果我正在运行需要一段时间才能完成的过程,这很烦人.
我可以让我的程序逐行写入进程输出,通过在循环结束之前轮询进程输出或其他内容吗?
**[编辑]抱歉,在发布此问题之前我没有很好地搜索.线程实际上是关键.在这里找到一个示例,说明如何执行此操作:** 来自线程的Python Subprocess.Popen
有没有办法在Python中指定命令的运行目录subprocess.Popen()?
例如:
Popen('c:\mytool\tool.exe', workingdir='d:\test\local')
Run Code Online (Sandbox Code Playgroud)
我的Python脚本位于 C:\programs\python
是否可以C:\mytool\tool.exe在目录中运行D:\test\local?
如何设置子流程的工作目录?
使用Python的subprocess模块和communicate()方法时如何检索退出代码?
相关代码:
import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
我应该这样做吗?
我正在使用python脚本作为流体动力学代码的驱动程序.当运行模拟时,我subprocess.Popen用来运行代码,从stdout和stderr收集输出到subprocess.PIPE---然后我可以打印(并保存到日志文件)输出信息,并检查是否有任何错误.问题是,我不知道代码是如何进展的.如果我直接从命令行运行它,它会给我输出关于它在什么时间迭代,什么时间,下一个时间步骤是什么等等的输出.
有没有办法既存储输出(用于记录和错误检查),还产生实时流输出?
我的代码的相关部分:
ret_val = subprocess.Popen( run_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True )
output, errors = ret_val.communicate()
log_file.write(output)
print output
if( ret_val.returncode ):
print "RUN failed\n\n%s\n\n" % (errors)
success = False
if( errors ): log_file.write("\n\n%s\n\n" % errors)
Run Code Online (Sandbox Code Playgroud)
最初我正在run_command通过管道,tee以便副本直接进入日志文件,并且流仍然直接输出到终端 - 但这样我就不能存储任何错误(对我的知识).
编辑:
临时解决方案:
ret_val = subprocess.Popen( run_command, stdout=log_file, stderr=subprocess.PIPE, shell=True )
while not ret_val.poll():
log_file.flush()
Run Code Online (Sandbox Code Playgroud)
然后,在另一个终端,运行tail -f log.txt(st log_file = 'log.txt').
我想从Python调用外部程序.我已经使用了两者Popen()并且call()做到了这一点.
这两者有什么区别?
我的具体目标是从Python运行以下命令.我不确定重定向是如何工作的.
./my_script.sh > output
Run Code Online (Sandbox Code Playgroud)
我阅读了文档,它说这call()是一个便利功能或快捷功能.我们是否通过使用call()代替Popen()?而失去了任何力量?
我正在尝试为命令行程序(svnadmin verify)编写一个包装器脚本,它将为操作显示一个很好的进度指示器.这要求我能够在输出后立即查看包装程序的每一行输出.
我想我只是执行程序使用subprocess.Popen,使用stdout=PIPE,然后读取每一行,并相应地对其进行操作.但是,当我运行以下代码时,输出似乎在某处缓冲,导致它出现在两个块中,第1行到第332行,然后是333到439(输出的最后一行)
from subprocess import Popen, PIPE, STDOUT
p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE,
stderr = STDOUT, shell = True)
for line in p.stdout:
print line.replace('\n', '')
Run Code Online (Sandbox Code Playgroud)
稍微查看子进程的文档后,我发现bufsize参数为Popen,所以我尝试将bufsize设置为1(缓冲每行)和0(无缓冲区),但这两个值似乎都没有改变行的传递方式.
此时我开始掌握吸管,所以我编写了以下输出循环:
while True:
try:
print p.stdout.next().replace('\n', '')
except StopIteration:
break
Run Code Online (Sandbox Code Playgroud)
但得到了相同的结果.
是否有可能获得使用子进程执行的程序的"实时"程序输出?Python中是否有其他选项可以向前兼容(不是exec*)?
我试图运行一个程序在Python代码中进行一些系统调用subprocess.call(),这会引发以下错误:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)
我的实际Python代码如下:
url = "/media/videos/3cf02324-43e5-4996-bbdf-6377df448ae4.mp4"
real_path = "/home/chanceapp/webapps/chanceapp/chanceapp"+url
fake_crop_path = "/home/chanceapp/webapps/chanceapp/chanceapp/fake1"+url
fake_rotate_path = "/home/chanceapp/webapps/chanceapp.chanceapp/fake2"+url
crop = "ffmpeg -i %s -vf "%(real_path)+"crop=400:400:0:0 "+ "-strict -2 %s"%(fake_crop_path)
rotate = "ffmpeg -i %s -vf "%(fake_crop_path)+"transpose=1 "+"%s"%(fake_rotate_path)
move_rotated …Run Code Online (Sandbox Code Playgroud)