use*_*312 35 python subprocess
在Python中,调用命令subprocess
但不打扰其输出的最短和标准方法是什么.
我尝试过subprocess.call
它似乎返回输出.我并不担心,我只需要静默运行程序而不会使输出混乱.
如果它有帮助,我正在打电话pdflatex
,我的意图就是打电话给它.
Sve*_*ach 51
如果您的进程产生大量输出而您不想在内存中缓冲,则应将输出重定向到电子垃圾箱:
with open(os.devnull, "w") as f:
subprocess.call(["pdflatex", filename], stdout=f)
Run Code Online (Sandbox Code Playgroud)
该变量os.devnull
是操作系统的空设备的名称(/dev/null
在大多数操作系统上,nul
在另一个操作系统上).
San*_*nta 38
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
# do something with out, err, or don't bother altogether.
Run Code Online (Sandbox Code Playgroud)
基本上,这"管道" cmd
输出到stdout和stderr到内存缓冲区的任何输出subprocess
.你对这些缓冲区的内容做了什么取决于你.你可以检查它们,或者完全不打扰它们.但是管道对这些缓冲区的副作用是它们不会被打印到终端上.
编辑:这也适用于方便的方法,call
.为了演示:
>>> subprocess.call('ping 127.0.0.1')
Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
0
>>> subprocess.call('ping 127.0.0.1', stdout=subprocess.PIPE)
0
Run Code Online (Sandbox Code Playgroud)
编辑-2:注意subprocess.call
:
注意:不要在此函数中使用stdout = PIPE或stderr = PIPE.由于在当前进程中没有读取管道,子进程可能会阻塞它是否为管道生成足够的输出以填充OS管道缓冲区.
归档时间: |
|
查看次数: |
50743 次 |
最近记录: |