IPython的性能更换!shellcommand博士

2024-04-24 00:23:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在Google Colab上,使用:

! shell-command

非常慢。你知道吗

下面是一个测试:

import os
%timeit os.system('date > /dev/null')
%timeit ! date > /dev/null

提供输出:

100 loops, best of 3: 8.58 ms per loop
1 loop, best of 3: 1.56 s per loop

这使得对一个简单命令使用! command比使用system()慢180倍。你知道吗

如何避免使用! command,同时仍将stdout/stderr实时写入输出单元?你知道吗

特别是,我希望能够在单个屏幕行上显示wget的动态进度条,但我会满足于为每个进度条更新写一行新行的解决方案。你知道吗


Tags: of进度条devloopdateosgoogleshell
2条回答

Python Run External Command And Get Output On Screen or In Variable给出:

import subprocess, sys

## command to run - tcp only ##
cmd = "/usr/sbin/netstat -p tcp -f inet"

## run it ##
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)

## But do not wait till netstat finish, start displaying output immediately ##
while True:
    out = p.stderr.read(1)
    if out == '' and p.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

请注意,这不会捕获或打印STDERR。欢迎编辑。你知道吗

你可以试试subprocess.check_output。它的工作原理类似于!,但是您需要首先将命令拆分为数组。你知道吗

相关问题 更多 >