我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?


当前回答

一个简单的方式是使用OS模块:

import os
os.system('ls')

否则,您还可以使用子过程模块:

import subprocess
subprocess.check_call('ls')

如果您希望结果存储在变量中,请尝试:

import subprocess
r = subprocess.check_output('ls')

其他回答

下面是一个Python脚本,它将在Ubuntu上运行命令,同时在实时显示日志:

command = 'your command here'    
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while True:
        output = process.stdout.readline().decode()
        if output == '' and process.poll() is not None:
            break
        if output:
            print(output.strip())
    rc = process.poll()
    if rc == 0:
        print("Command succeeded.")
       
    else:
        print("Command failed.")

我总是使用纺织品来做这些事情,这里是一个演示代码:

from fabric.operations import local
result = local('ls', capture=True)
print "Content:/n%s" % (result, )

但这似乎是一个很好的工具:sh(Python子处理界面)。

看看一个例子:

from sh import vgdisplay
print vgdisplay()
print vgdisplay('-v')
print vgdisplay(v=True)

使用副过程。

或者一个非常简单的命令:

import os
os.system('cat testfile')

我为此写了一本图书馆,shell.py。

它基本上是现在的旋转器和旋转器,它还支持旋转命令,所以你可以在Python中更容易进行连锁命令,所以你可以做这样的事情:

ex('echo hello shell.py') | "awk '{print $2}'"

对于 Python 3.5+ 而言,建议您从子过程模块中使用运行函数,这将返回一个完整的过程对象,您可以轻松地获得输出和返回代码。

from subprocess import PIPE, run

command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)