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


import os
os.system("your command")

请注意,这是危险的,因为命令没有清理,我将其留给谷歌有关“骨”和“骨”模块的文档,有许多功能(exec*和spawn*)将做类似的事情。

import os
cmd = 'ls -al'
os.system(cmd)

如果你想返回命令的结果,你可以使用os.popen. 但是,这是由于版本 2.6 有利于子过程模块,其他答案已经覆盖得很好。

步骤1:添加模块

import subprocess
subprocess.run(["ls", "-l"])

步骤2:呼叫外部命令

import subprocess

result = subprocess.run(["ls"], capture_output=True)
print(result.stdout)

提示: shlex.split() 方法可以用来将简单的 shell 命令分解到单个论点,但它可能不会正确地与包含管道符号的更长和更复杂的命令一起工作,这可能会使漏洞变得困难。

安全影响:在运行外部命令时,您应该小心正确逃避包含特殊字符的任何论点,因为它们可能会被阴影以意想不到的方式解释。


子过程模块提供了更强大的设施,以便扫描新过程并获取其结果;使用该模块,最好使用此功能。 请参见子过程模块部分的替代老功能,在子过程文档中找到一些有用的食谱。


注意: 在 Python 3.4 或更高版本中,使用 subprocess.call 而不是.run:

subprocess.call(["ls", "-l"])

如果您使用 Python 3.5 +,请使用 subprocess.run()。

我会建议使用子过程模块而不是os.system,因为它会让您逃脱,因此更安全。

subprocess.call(['ping', 'localhost'])

使用副过程。

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

import os
os.system('cat testfile')

os.system 是 OK,但类型的日期. 它也不是很安全. 相反,尝试 subprocess. subprocess 不直接呼叫 sh 因此比 os.system 更安全。

在这里获取更多信息

下面是如何呼叫外部程序的概述,包括其优点和缺点:

os.system 将命令和论点转移到您的系统的阴道. 这很好,因为您实际上可以以这种方式同时运行多个命令,并设置管道和输入/输出重定向。 例如: os.system(“some_command < input_file♰ another_command > output_file”) 但是,虽然这是方便的,您必须手动处理阴道字符的逃避,如空间,和

副过程模块应该是你所使用的。

最后,请注意,对于你通过的所有方法,最终命令将由丝带执行,你负责逃避它。 有严重的安全影响,如果你通过的丝带的任何部分不能完全信任。 例如,如果用户进入某些 / 任何部分的丝带. 如果你不确定,只使用这些方法的连续。

print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()

想象一下,用户输入了一些“我的妈妈不喜欢我&rm -rf /”可以删除整个文件系统。

典型的实施:

import subprocess

p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
    print line,
retval = p.wait()

事实上,你可以简单地忽略这些参数(stdout=和stderr=)并将像os.system()一样行事。

这里还有另一个区别,以前没有提到。

subprocess.Popen 执行 <命令> 作为一个子过程. 在我的情况下,我需要执行与另一个程序, <b> 沟通的 <a> 文件。

我尝试了子过程,执行成功了,但是 <b> 无法与 <a> 沟通,当我从终端运行时,一切都正常。

另外一个: (注意: kwrite 与其他应用程序不同,如果您尝试下面的 Firefox,结果将不相同。

如果你尝试 os.system(“kwrite”),程序流冻结,直到用户关闭 kwrite. 为了克服我尝试了 os.system(控制台 -e kwrite)。 这次程序继续流动,但 kwrite 成为控制台的子过程。

任何人运行基里特不是一个子过程(即在系统监控器中,它必须出现在树的左边)。

假设你想从一个 CGI 脚本开始一个漫长的任务,也就是说,孩子的过程应该比 CGI 脚本执行过程更长。

从子过程模块文档的经典例子是:

import subprocess
import sys

# Some code here

pid = subprocess.Popen([sys.executable, "longtask.py"]) # Call subprocess

# Some more code here

我的目标平台是FreeBSD,但开发是在Windows上,所以我首先面对了Windows上的问题。

在Windows(Windows XP)上,父母过程不会完成,直到 longtask.py 完成了工作。 这不是你想要的 CGI 脚本. 问题不是具体的 Python; 在 PHP 社区,问题是相同的。

解决方案是将 DETACHED_PROCESS Process Creation Flag 转移到 Windows API 中的 CreateProcess 功能。 如果您安装了 pywin32,您可以从 win32 过程模块中导入旗帜,否则您应该自己定义:

DETACHED_PROCESS = 0x00000008

pid = subprocess.Popen([sys.executable, "longtask.py"],
                       creationflags=DETACHED_PROCESS).pid

pid = subprocess.Popen([sys.executable, "longtask.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

我没有在其他平台上检查代码,也不知道FreeBSD的行为原因,如果有人知道的话,请分享你的想法。

查看Python图书馆的“快速”图书馆,也。

它允许对外程序 / 命令的互动控制,甚至 ssh, ftp, telnet 等。

child = pexpect.spawn('ftp 192.168.0.24')

child.expect('(?i)name .*: ')

child.sendline('anonymous')

child.expect('(?i)password')

subprocess.check_call 是方便的,如果你不想测试返回值。

如果您需要从您正在呼叫的命令中输出,那么您可以使用 subprocess.check_output (Python 2.7+)。

>>> subprocess.check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

请注意Shell参数。

如果阴道是真实的,指定的命令将通过阴道执行,这可能是有用的,如果你使用Python主要是为了增强的控制流,它提供了超过大多数系统阴道,仍然想要方便的访问其他阴道功能,如阴道管,字体名称野地图,环境变量扩展,并扩展 ~ 到用户的主目录。

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

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)

os.system 不允许您存储结果,所以如果您想要存储结果在某些列表或某些东西,一个 subprocess.call 工作。

您可以使用Popen,然后您可以检查程序的状态:

from subprocess import Popen

proc = Popen(['ls', '-l'])
if proc.poll() is None:
    proc.kill()

查看 subprocess.Popen。

最简单的方式运行任何命令,并获得结果:

from commands import getstatusoutput

try:
    return getstatusoutput("ls -ltr")
except Exception, e:
    return None

这就是我如何运行我的命令. 这个代码有你需要的一切

from subprocess import Popen, PIPE
cmd = "ls -l ~/"
p = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
print "Return code: ", p.returncode
print out.rstrip(), err.rstrip()

更新:

subprocess.run 是关于 Python 3.5 的推荐方法,如果您的代码不需要与以前的 Python 版本保持兼容性。

下面是文档的一些例子。

运行一个过程:

>>> subprocess.run(["ls", "-l"])  # Doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

上一篇: 失败的跑步:

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

捕获输出:

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

原始答案:

我建议尝试发送,这是一个子过程的插槽,其目的是取代旧的模块和功能。

使用 README 的例子:

>>> r = envoy.run('git config', data='data to pipe in', timeout=2)

>>> r.status_code
129
>>> r.std_out
'usage: git config [options]'
>>> r.std_err
''

周围的管道也:

>>> r = envoy.run('uptime | pbcopy')

>>> r.command
'pbcopy'
>>> r.status_code
0

>>> r.history
[<Response 'uptime'>]

与标准图书馆

使用子过程模块(Python 3):

import subprocess
subprocess.run(['ls', '-l'])

但是,更复杂的任务(管道,输出,输入等)可以是无聊的构建和写作。

注意 Python 版本: 如果您仍然使用 Python 2, subprocess.call 以类似的方式运行。

ProTip: shlex.split 可以帮助您打破运行命令、呼叫和其他子过程功能,如果您不希望(或您不能!)以列表的形式提供它们:

import shlex
import subprocess
subprocess.run(shlex.split('ls -l'))

与外部依赖

如果你不注意外部依赖,使用铅:

from plumbum.cmd import ifconfig
print(ifconfig['wlan0']())

它是最好的子处理器. 它是跨平台,即它在Windows和Unix类似的系统上运行。

另一个受欢迎的图书馆是:

from sh import ifconfig
print(ifconfig('wlan0'))

然而,sh下降了Windows支持,所以它不像它以前那样令人惊叹。

还有不同的方式来处理返回代码和错误,你可能想打破输出,并提供新的输入(在预期类型的风格)。或者你将需要重新引导标准输入,标准输出和标准错误运行在不同的tty(例如,当使用GNU屏幕)。

因此,这里是我们写的Python模块,可以处理你想要的几乎任何东西,如果没有,它是非常灵活的,所以你可以轻松地扩展它:

它不单独工作,需要一些我们的其他工具,并在过去的几年里获得了很多专门的功能,所以它可能不是一个下降的替代品,但它可以给你很多关于如何运行命令的Python内部工作以及如何处理某些情况的想法。

2015 年更新: Python 3.5 添加了 subprocess.run 比 subprocess.Popen 更容易使用。

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')

只需添加到讨论中,如果您使用 Python 控制台,您可以从 IPython 呼叫外部命令,而在 IPython 快速时,您可以通过预定“!”。您也可以将 Python 代码与 Shell 结合起来,并将 Shell 脚本的输出分配给 Python 变量。

例如:

In [9]: mylist = !ls

In [10]: mylist
Out[10]:
['file1',
 'file2',
 'file3',]

经过一些研究,我有下面的代码,这对我来说非常好,它基本上在实时打印了标准输出和标准错误。

stdout_result = 1
stderr_result = 1


def stdout_thread(pipe):
    global stdout_result
    while True:
        out = pipe.stdout.read(1)
        stdout_result = pipe.poll()
        if out == '' and stdout_result is not None:
            break

        if out != '':
            sys.stdout.write(out)
            sys.stdout.flush()


def stderr_thread(pipe):
    global stderr_result
    while True:
        err = pipe.stderr.read(1)
        stderr_result = pipe.poll()
        if err == '' and stderr_result is not None:
            break

        if err != '':
            sys.stdout.write(err)
            sys.stdout.flush()


def exec_command(command, cwd=None):
    if cwd is not None:
        print '[' + ' '.join(command) + '] in ' + cwd
    else:
        print '[' + ' '.join(command) + ']'

    p = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
    )

    out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
    err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))

    err_thread.start()
    out_thread.start()

    out_thread.join()
    err_thread.join()

    return stdout_result + stderr_result

使用 subprocess.call:

from subprocess import call

# Using list
call(["echo", "Hello", "world"])

# Single string argument varies across platforms so better split it
call("echo Hello world".split(" "))

我倾向于与shlex一起使用子过程(以处理引用的绳子的逃避):

>>> import subprocess, shlex
>>> command = 'ls -l "/your/path/with spaces/"'
>>> call_params = shlex.split(command)
>>> print call_params
["ls", "-l", "/your/path/with spaces/"]
>>> subprocess.call(call_params)

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

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

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

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

import os
os.system('ls')

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

import subprocess
subprocess.check_call('ls')

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

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

还有铅

>>> from plumbum import local
>>> ls = local["ls"]
>>> ls
LocalCommand(<LocalPath /bin/ls>)
>>> ls()
u'build.py\ndist\ndocs\nLICENSE\nplumbum\nREADME.rst\nsetup.py\ntests\ntodo.txt\n'
>>> notepad = local["c:\\windows\\notepad.exe"]
>>> notepad()                                   # Notepad window pops up
u''                                             # Notepad window is closed by user, command returns

使用:

import os

cmd = 'ls -al'

os.system(cmd)

os - 此模块提供一个可携带的方式来使用操作系统依赖的功能。

对于更多的 OS 功能,这里是文档。

使用Python模块的Popen函数是运行Linux命令的最简单方式,Popen.communicate()函数将为您的命令提供输出。

import subprocess

..
process = subprocess.Popen(..)   # Pass command and arguments to the function
stdout, stderr = process.communicate()   # Get command output and error
..

下面是我的两个百分点:在我看来,这是处理外部命令时最好的做法......

这些是执行方法的回报值......

pass, stdout, stderr = execute(["ls","-la"],"/home/user/desktop")

这是执行方法......

def execute(cmdArray,workingDir):

    stdout = ''
    stderr = ''

    try:
        try:
            process = subprocess.Popen(cmdArray,cwd=workingDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
        except OSError:
            return [False, '', 'ERROR : command(' + ' '.join(cmdArray) + ') could not get executed!']

        for line in iter(process.stdout.readline, b''):

            try:
                echoLine = line.decode("utf-8")
            except:
                echoLine = str(line)

            stdout += echoLine

        for line in iter(process.stderr.readline, b''):

            try:
                echoLine = line.decode("utf-8")
            except:
                echoLine = str(line)

            stderr += echoLine

    except (KeyboardInterrupt,SystemExit) as err:
        return [False,'',str(err)]

    process.stdout.close()

    returnCode = process.wait()
    if returnCode != 0 or stderr != '':
        return [False, stdout, stderr]
    else:
        return [True, stdout, stderr]

对于 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)

我会推荐下面的“运行”方法,它会帮助我们获得标准输出、标准错误和输出状态作为词典;这个词典的呼叫者可以通过“运行”方法阅读词典返回,以了解过程的实际状态。

  def run (cmd):
       print "+ DEBUG exec({0})".format(cmd)
       p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)
       (out, err) = p.communicate()
       ret        = p.wait()
       out        = filter(None, out.split('\n'))
       err        = filter(None, err.split('\n'))
       ret        = True if ret == 0 else False
       return dict({'output': out, 'error': err, 'status': ret})
  #end

在 Windows 中,您只能输入子过程模块并运行外部命令,以下列方式呼叫 subprocess.Popen(), subprocess.Popen().communicate() 和 subprocess.Popen().wait():

# Python script to run a command line
import subprocess

def execute(cmd):
    """
        Purpose  : To execute a command and return exit status
        Argument : cmd - command to execute
        Return   : exit_code
    """
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (result, error) = process.communicate()

    rc = process.wait()

    if rc != 0:
        print "Error: failed to execute command:", cmd
        print error
    return result
# def

command = "tasklist | grep python"
print "This process detail: \n", execute(command)

出口:

This process detail:
python.exe                     604 RDP-Tcp#0                  4      5,660 K

使用:

import subprocess

p = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
print p.split("\n")

它提供良好的产量,更容易与:

['Filesystem      Size  Used Avail Use% Mounted on',
 '/dev/sda6        32G   21G   11G  67% /',
 'none            4.0K     0  4.0K   0% /sys/fs/cgroup',
 'udev            1.9G  4.0K  1.9G   1% /dev',
 'tmpfs           387M  1.4M  386M   1% /run',
 'none            5.0M     0  5.0M   0% /run/lock',
 'none            1.9G   58M  1.9G   3% /run/shm',
 'none            100M   32K  100M   1% /run/user',
 '/dev/sda5       340G  222G  100G  69% /home',
 '']

从 OpenStack Neutron 中获取网络 ID:

#!/usr/bin/python
import os
netid = "nova net-list | awk '/ External / { print $2 }'"
temp = os.popen(netid).read()  /* Here temp also contains new line (\n) */
networkId = temp.rstrip()
print(networkId)

新网列表

+--------------------------------------+------------+------+
| ID                                   | Label      | CIDR |
+--------------------------------------+------------+------+
| 431c9014-5b5d-4b51-a357-66020ffbb123 | test1      | None |
| 27a74fcd-37c0-4789-9414-9531b7e3f126 | External   | None |
| 5a2712e9-70dc-4b0e-9281-17e02f4684c9 | management | None |
| 7aa697f5-0e60-4c15-b4cc-9cb659698512 | Internal   | None |
+--------------------------------------+------------+------+

印刷输出(networkId)

27a74fcd-37c0-4789-9414-9531b7e3f126

有很多方法可以命令。

例如:

如果 and.exe 需要 2 个参数. 在 cmd 我们可以呼叫 sample.exe 使用此: and.exe 2 3 并在屏幕上显示 5。

如果我们使用 Python 脚本来呼叫 and.exe,我们应该这样做。

os.system(cmd,...) os.system(("and.exe" + "" + "2" + " + "3") os.popen(cmd,...) os.popen(("and.exe" + " + "2" + " + "3")) subprocess.Popen(cmd,...) subprocess.Popen(("and.exe" + " + "2" + " + "3"))

它太硬了,所以我们可以与一个空间加入CMD:

import os
cmd = " ".join(exename,parameters)
os.popen(cmd)

下面是呼叫外部命令并返回或打印命令的输出:

Python Subprocess check_output 有好处

使用论点执行命令,并将其输出作为比特行返回。

import subprocess
proc = subprocess.check_output('ipconfig /all')
print proc

有很多不同的图书馆,允许您使用Python呼叫外部命令. 对于每个图书馆,我给了一个描述,并显示了一个例子呼叫外部命令. 我使用的命令作为例子是ls -l(列出所有文件)。 如果你想了解更多关于任何图书馆,我列出并链接到文件的每一个。

来源

这些都是图书馆

希望这会帮助你做出决定哪个图书馆使用:)

副过程

subprocess.run(["ls", "-l"]) # Run command
subprocess.run(["ls", "-l"], stdout=subprocess.PIPE) # This will run the command and return any output
subprocess.run(shlex.split("ls -l")) # You can also use the shlex library to split the command

os 用于“操作系统依赖功能”。 它也可以用来呼叫与 os.system 和 os.popen 的外部命令(注:也有 subprocess.popen)。 os 总是会运行盾牌,并且对于那些不需要或不知道如何使用 subprocess.run 的人来说是一个简单的替代方案。

os.system("ls -l") # Run command
os.popen("ls -l").read() # This will run the command and return any output

饰 sh

sh 是一个子过程界面,允许您呼叫程序,就好像它们是功能。

sh.ls("-l") # Run command normally
ls_cmd = sh.Command("ls") # Save command as a variable
ls_cmd() # Run command as if it were a function

ls_cmd = plumbum.local("ls -l") # Get command
ls_cmd() # Run command

佩克斯

pexpect.run("ls -l") # Run command as normal
child = pexpect.spawn('scp foo user@example.com:.') # Spawns child application
child.expect('Password:') # When this is the output
child.sendline('mypassword')

织物

fabric.operations.local('ls -l') # Run command as normal
fabric.operations.local('ls -l', capture = True) # Run command and receive output

发送

r = envoy.run("ls -l") # Run command
r.std_out # Get output

命令

在Linux中,如果您想打电话给一个将独立执行的外部命令(在Python脚本结束后将继续运行),您可以使用一个简单的字符串作为任务插槽或命令中的命令。

例如,Task Spooler:

import os
os.system('ts <your-command>')

關於Task Spooler(TS)的評論:

您可以设置要运行的竞争对手过程的数量(“插槽”)与: ts -S <插槽的号码> 安装 ts 不需要管理特权. 您可以从源头下载并编写一个简单的创建,将其添加到您的路径,并完成。

>>> from subprocess import run
>>> from shlex import split
>>> completed_process = run(split('python --version'))
Python 3.8.8
>>> completed_process
CompletedProcess(args=['python', '--version'], returncode=0)

下面是最简单的使用的例子 - 它正如所要求的那样:

>>> from subprocess import run
>>> from shlex import split
>>> completed_process = run(split('python --version'))
Python 3.8.8
>>> completed_process
CompletedProcess(args=['python', '--version'], returncode=0)

>>> completed_process.args
['python', '--version']
>>> completed_process.returncode
0

如果您想捕获输出,您可以将 subprocess.PIPE 转移到适当的 stderr 或 stdout:

>>> from subprocess import PIPE
>>> completed_process = run(shlex.split('python --version'), stdout=PIPE, stderr=PIPE)
>>> completed_process.stdout
b'Python 3.8.8\n'
>>> completed_process.stderr
b''

相应的属性返回比特。

>>> import textwrap
>>> args = ['python', textwrap.__file__]
>>> cp = run(args, stdout=subprocess.PIPE)
>>> cp.stdout
b'Hello there.\n  This is indented.\n'

下面是源头的真实签名,如助(run)所示:

输入可以是一个字符串(或单码,如果指定编码或 universal_newlines=True)将被带到子过程的stdin。

这个 check=true 的例子比我可以看到的更好:

波恩


def __init__(self, args, bufsize=-1, executable=None,
             stdin=None, stdout=None, stderr=None,
             preexec_fn=None, close_fds=True,
             shell=False, cwd=None, env=None, universal_newlines=None,
             startupinfo=None, creationflags=0,
             restore_signals=True, start_new_session=False,
             pass_fds=(), *, user=None, group=None, extra_groups=None,
             encoding=None, errors=None, text=None, umask=-1, pipesize=-1):

了解Popen的剩余文档将作为读者的练习留下来。

我写了一封信来处理错误,并重新引导输出和其他东西。

import shlex
import psutil
import subprocess

def call_cmd(cmd, stdout=sys.stdout, quiet=False, shell=False, raise_exceptions=True, use_shlex=True, timeout=None):
    """Exec command by command line like 'ln -ls "/var/log"'
    """
    if not quiet:
        print("Run %s", str(cmd))
    if use_shlex and isinstance(cmd, (str, unicode)):
        cmd = shlex.split(cmd)
    if timeout is None:
        process = subprocess.Popen(cmd, stdout=stdout, stderr=sys.stderr, shell=shell)
        retcode = process.wait()
    else:
        process = subprocess.Popen(cmd, stdout=stdout, stderr=sys.stderr, shell=shell)
        p = psutil.Process(process.pid)
        finish, alive = psutil.wait_procs([p], timeout)
        if len(alive) > 0:
            ps = p.children()
            ps.insert(0, p)
            print('waiting for timeout again due to child process check')
            finish, alive = psutil.wait_procs(ps, 0)
        if len(alive) > 0:
            print('process {} will be killed'.format([p.pid for p in alive]))
            for p in alive:
                p.kill()
            if raise_exceptions:
                print('External program timeout at {} {}'.format(timeout, cmd))
                raise CalledProcessTimeout(1, cmd)
        retcode = process.wait()
    if retcode and raise_exceptions:
        print("External program failed %s", str(cmd))
        raise subprocess.CalledProcessError(retcode, cmd)

你可以这样称之为:

cmd = 'ln -ls "/var/log"'
stdout = 'out.txt'
call_cmd(cmd, stdout)

作为一个例子(在Linux):

import subprocess
subprocess.run('mkdir test.dir', shell=True)

这在当前目录中创建 test.dir. 请注意,这也是有效的:

import subprocess
subprocess.call('mkdir test.dir', shell=True)

使用 os.system 的同等代码是:

import os
os.system('mkdir test.dir')

最好的做法是使用子过程而不是OS,与.run 受欢迎的.call. 所有你需要知道的子过程在这里. 此外,请注意,所有的 Python 文档都可以从这里下载. 我下载了 PDF 包装为.zip. 我提到这一点,因为有一个好概述的OS 模块在 tutorial.pdf (页面 81 ) 。 此外,它是一个授权的资源的 Python 编码器。

我常常用下列函数用于外部命令,这特别适用于长时间运行过程,下面的方法在运行时将过程输出缩短,并返回输出,如果过程失败,则会产生一个例外。

结果是,如果这个过程是通过 poll() 方法完成的。

import subprocess,sys

def exec_long_running_proc(command, args):
    cmd = "{} {}".format(command, " ".join(str(arg) if ' ' not in arg else arg.replace(' ','\ ') for arg in args))
    print(cmd)
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # Poll process for new output until finished
    while True:
        nextline = process.stdout.readline().decode('UTF-8')
        if nextline == '' and process.poll() is not None:
            break
        sys.stdout.write(nextline)
        sys.stdout.flush()

    output = process.communicate()[0]
    exitCode = process.returncode

    if (exitCode == 0):
        return output
    else:
        raise Exception(command, exitCode, output)

你可以这样引用它:

exec_long_running_proc(command = "hive", args=["-f", hql_path])

在Python中呼叫外部命令

一个简单的方式来呼叫一个外部命令是使用os.system(...). 这个功能返回命令的输出值. 但缺点是我们不会得到 stdout 和 stderr。

ret = os.system('some_cmd.sh')
if ret != 0 :
    print 'some_cmd.sh execution returned failure'

在背景下在Python中呼叫外部命令

subprocess.Popen 提供更多的灵活性运行一个外部命令而不是使用 os.system. 我们可以在背景下启动一个命令,等待它完成。

proc = subprocess.Popen(["./some_cmd.sh"], stdout=subprocess.PIPE)
print 'waiting for ' + str(proc.pid)
proc.wait()
print 'some_cmd.sh execution finished'
(out, err) = proc.communicate()
print 'some_cmd.sh output : ' + out

在背景下在Python中呼叫一个长期运行的外部命令,并在一段时间后停止

我们甚至可以在背景下开始一个漫长的运行过程,使用subprocess.Popen,并在任务完成后一次杀死它。

proc = subprocess.Popen(["./some_long_run_cmd.sh"], stdout=subprocess.PIPE)
# Do something else
# Now some_long_run_cmd.sh exeuction is no longer needed, so kill it
os.system('kill -15 ' + str(proc.pid))
print 'Output : ' proc.communicate()[0]

可以是这样简单的:

import os
cmd = "your command"
os.system(cmd)

如果您需要从 Python 笔记本电脑(如 Jupyter、Zeppelin、Databricks 或 Google Cloud Datalab)中拨打一个支票命令,您只能使用! 预定。

例如,

!ls -ilF

Invoke 是一个 Python (2.7 和 3.4+) 任务执行工具和图书馆. 它提供清洁,高级别的 API 运行 Shell 命令:

>>> from invoke import run
>>> cmd = "pip install -r requirements.txt"
>>> result = run(cmd, hide=True, warn=True)
>>> print(result.ok)
True
>>> print(result.stdout.splitlines()[-1])
Successfully installed invocations-0.13.0 pep8-1.5.7 spec-1.3.1

我写了一本小图书馆来帮助这个使用案例:

HTTPS://pypi.org/project/citizenshell/

可以使用安装

pip install citizenshell

然后使用如下:

from citizenshell import sh
assert sh("echo Hello World") == "Hello World"

您可以将标准输出与标准错误分开,并以以下方式提取输出代码:

result = sh(">&2 echo error && echo output && exit 13")
assert result.stdout() == ["output"]
assert result.stderr() == ["error"]
assert result.exit_code() == 13

而且很酷的是,在开始处理输出之前,你不需要等待底层的裂缝出发:

for line in sh("for i in 1 2 3 4; do echo -n 'It is '; date +%H:%M:%S; sleep 1; done", wait=False)
    print ">>>", line + "!"

将按行按行按行按行按行按行按行按行按行。

>>> It is 14:24:52!
>>> It is 14:24:53!
>>> It is 14:24:54!
>>> It is 14:24:55!

更多例子可以找到 https://github.com/meuter/citizenshell

在Python 3.5+中使用子过程,以下是我在Linux上做的技巧:

import subprocess

# subprocess.run() returns a completed process object that can be inspected
c = subprocess.run(["ls", "-ltrh"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(c.stdout.decode('utf-8'))

正如文档中提到的那样,PIPE 值是比特序列,为了正确显示它们,应考虑解码。

上述代码的结果是:

total 113M
-rwxr-xr-x  1 farzad farzad  307 Jan 15  2018 vpnscript
-rwxrwxr-x  1 farzad farzad  204 Jan 15  2018 ex
drwxrwxr-x  4 farzad farzad 4.0K Jan 22  2018 scripts
.... # Some other lines

如果您在命令中不使用用户输入,您可以使用以下操作:

from os import getcwd
from subprocess import check_output
from shlex import quote

def sh(command):
    return check_output(quote(command), shell=True, cwd=getcwd(), universal_newlines=True).strip()

用它作为

branch = sh('git rev-parse --abbrev-ref HEAD')

shell=True 将扫描一个阴道,所以你可以使用管道和这样的阴道事物 sh('ps auxibh grep python'). 这是非常方便的运行硬编码命令和处理其输出。

但这不是安全的用户输入,从文档:

安全考虑 与其他某些字符功能不同,此实施将永远不会随意称为系统字符,这意味着所有字符,包括字符字符字符,都可以安全地转移到儿童过程,如果字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符

In [50]: timeit("check_output('ls -l'.split(), universal_newlines=True)", number=1000, globals=globals())
Out[50]: 2.6801227919995654

In [51]: timeit("check_output('ls -l', universal_newlines=True, shell=True)", number=1000, globals=globals())
Out[51]: 3.243950183999914

苏丹是一个最近为此而设计的包,它提供了管理用户特权和添加有用的错误消息的一些好处。

from sultan.api import Sultan

with Sultan.load(sudo=True, hostname="myserver.com") as sultan:
  sultan.yum("install -y tree").run()

如果您正在写一个 Python shell 脚本,并且在您的系统上安装了 IPython,您可以使用 bang 预定来在 IPython 中运行一个 shell 命令:

!ls
filelist = !ls

Python 3.5 以上

import subprocess

p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())

网上尝试

import subprocess

p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())

网上尝试

os.popen() 是执行命令的最简单和最安全的方式. 您可以在命令行上执行任何命令. 此外,您还将能够使用 os.popen().read() 捕获命令的输出。

你可以这样做:

import os
output = os.popen('Your Command Here').read()
print (output)

例如,您列出当前目录中的所有文件:

import os
output = os.popen('ls').read()
print (output)
# Outputs list of files in the directory

最多案例:

在大多数情况下,一个短片的代码,如此,是你将需要的一切:

import subprocess
import shlex

source = "test.txt"
destination = "test_copy.txt"

base = "cp {source} {destination}'"
cmd = base.format(source=source, destination=destination)
subprocess.check_call(shlex.split(cmd))

它是干净和简单的。

subprocess.check_call 以论点运行命令,等待命令完成。 shlex.split 使用 shell-like syntax 分割行 cmd

其他案例:

如果这不适用于某些特定的命令,最有可能你有一个问题与命令线的解释器. 操作系统选择了默认一个不适合你的程序类型或可能没有找到适当的一个在系统可执行的路径。

例子:

使用Unix系统上的转向操作器

input_1 = "input_1.txt"
input_2 = "input_2.txt"
output = "merged.txt"
base_command = "/bin/bash -c 'cat {input} >> {output}'"

base_command.format(input_1, output=output)
subprocess.check_call(shlex.split(base_command))

base_command.format(input_2, output=output)
subprocess.check_call(shlex.split(base_command))

正如《Python Zen: Explicit is better than implicit》中所说的那样。

因此,如果使用 Python >=3.6 函数,它会看起来像这样:

import subprocess
import shlex

def run_command(cmd_interpreter: str, command: str) -> None:
    base_command = f"{cmd_interpreter} -c '{command}'"
    subprocess.check_call(shlex.split(base_command)

import subprocess as s
s.call(["command.exe", "..."])

通话函数将启动外部过程,通过一些命令线论点,等待它完成。当它完成时,您将继续执行.通话函数中的论点通过列表.列表中的第一个论点是命令通常以执行文件的形式,随后在列表中的论点,您想要通过什么。

最终,在列表后,有几个选项参数其中一个是阴影,如果你设置阴影等于真实,那么你的命令将运行,就像你在命令即时输入一样。

s.call(["command.exe", "..."], shell=True)

s.check_call(...)

最后,如果你想要更紧的控制Popen构建器,这也是从子过程模块。 它也需要相同的论点作为incall & check_call 函数,但它返回一个代表运行过程的对象。

p=s.Popen("...")

我用的是Python 3.6+:

import subprocess
def execute(cmd):
    """
        Purpose  : To execute a command and return exit status
        Argument : cmd - command to execute
        Return   : result, exit_code
    """
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (result, error) = process.communicate()
    rc = process.wait()
    if rc != 0:
        print ("Error: failed to execute command: ", cmd)
        print (error.rstrip().decode("utf-8"))
    return result.rstrip().decode("utf-8"), serror.rstrip().decode("utf-8")
# def


TL;DR 2021年

import subprocess
subprocess.run("ls -a", shell=True)

注意:这是对你的问题的准确答案 - 执行命令

就像在沙子里


偏好之路

如果可能的话,移除箭头顶部并直接运行命令(需要列表)。

import subprocess
subprocess.run(["help"])
subprocess.run(["ls", "-a"])


检查输出

下列代码本身就是:

import subprocess
result = subprocess.run(["ls", "-a"], capture_output=True, text=True)
if "stackoverflow-logo.png" in result.stdout:
    print("You're a fan!")
else:
    print("You're not a fan?")

查看返回代码

if result.returncode == 127: print("The program failed for some weird reason")
elif result.returncode == 0: print("The program succeeded")
else: print("The program failed unexpectedly")

result.check_returncode()

result = subprocess.run(..., check=True)

result = subprocess.run(..., stderr=subprocess.STDOUT)

使用shell=False 与论点字符串

import subprocess
import shlex
subprocess.run(shlex.split("ls -a"))

常见问题

FileNotFoundError: [Errno 2] 没有此类文件或目录: 'ls -a': 'ls -a'

此分類上一篇: NoneType [...]

确保您已设置 capture_output=True。

您总是从您的程序中获取比特结果. 如果您想像正常字符串一样使用它,则设置文本=真实。

您可以使用 Popen 从子过程模块运行任何命令。

from subprocess import Popen

首先,一个命令对象是创建的,所有你想要运行的论点。 例如,在下面的剪辑中,指令对象是由所有论点组成的:

cmd = (
        "gunicorn "
        "-c gunicorn_conf.py "
        "-w {workers} "
        "--timeout {timeout} "
        "-b {address}:{port} "
        "--limit-request-line 0 "
        "--limit-request-field_size 0 "
        "--log-level debug "
        "--max-requests {max_requests} "
        "manage:app").format(**locals())

然后这个命令对象与Popen一起使用,以启动一个过程:

process = Popen(cmd, shell=True)

这个过程也可以根据任何信号结束,使用下面的代码线:

Popen.terminate(process)

你可以等到完成上述命令的执行:

process.wait()

这里有很多答案,但没有一个满足了我所有的需求。

我需要运行命令并捕获输出和输出代码. 我需要时间out 执行的程序,并强迫它出去,如果时间out 达到,并杀死它的所有儿童过程. 我需要它在 Windows XP 和以后, Cygwin 和 Linux 工作。

def _run(command, timeout_s=False, shell=False):
    ### run a process, capture the output and wait for it to finish. if timeout is specified then Kill the subprocess and its children when the timeout is reached (if parent did not detach)
    ## usage: _run(arg1, arg2, arg3)
        # arg1: command + arguments. Always pass a string; the function will split it when needed
        # arg2: (optional) timeout in seconds before force killing
        # arg3: (optional) shell usage. default shell=False
    ## return: a list containing: exit code, output, and if timeout was reached or not

    # - Tested on Python 2 and 3 on Windows XP, Windows 7, Cygwin and Linux.
    # - preexec_fn=os.setsid (py2) is equivalent to start_new_session (py3) (works on Linux only), in Windows and Cygwin we use TASKKILL
    # - we use stderr=subprocess.STDOUT to merge standard error and standard output
    import sys, subprocess, os, signal, shlex, time

    def _runPY3(command, timeout_s=None, shell=False):
        # py3.3+ because: timeout was added to communicate() in py3.3.
        new_session=False
        if sys.platform.startswith('linux'): new_session=True
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=new_session, shell=shell)

        try:
            out = p.communicate(timeout=timeout_s)[0].decode('utf-8')
            is_timeout_reached = False
        except subprocess.TimeoutExpired:
            print('Timeout reached: Killing the whole process group...')
            killAll(p.pid)
            out = p.communicate()[0].decode('utf-8')
            is_timeout_reached = True
        return p.returncode, out, is_timeout_reached

    def _runPY2(command, timeout_s=0, shell=False):
        preexec=None
        if sys.platform.startswith('linux'): preexec=os.setsid
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=preexec, shell=shell)

        start_time = time.time()
        is_timeout_reached = False
        while timeout_s and p.poll() == None:
            if time.time()-start_time >= timeout_s:
                print('Timeout reached: Killing the whole process group...')
                killAll(p.pid)
                is_timeout_reached = True
                break
            time.sleep(1)
        out = p.communicate()[0].decode('utf-8')
        return p.returncode, out, is_timeout_reached

    def killAll(ParentPid):
        if sys.platform.startswith('linux'):
            os.killpg(os.getpgid(ParentPid), signal.SIGTERM)
        elif sys.platform.startswith('cygwin'):
            # subprocess.Popen(shlex.split('bash -c "TASKKILL /F /PID $(</proc/{pid}/winpid) /T"'.format(pid=ParentPid)))
            winpid=int(open("/proc/{pid}/winpid".format(pid=ParentPid)).read())
            subprocess.Popen(['TASKKILL', '/F', '/PID', str(winpid), '/T'])
        elif sys.platform.startswith('win32'):
            subprocess.Popen(['TASKKILL', '/F', '/PID', str(ParentPid), '/T'])

    # - In Windows, we never need to split the command, but in Cygwin and Linux we need to split if shell=False (default), shlex will split the command for us
    if shell==False and (sys.platform.startswith('cygwin') or sys.platform.startswith('linux')):
        command=shlex.split(command)

    if sys.version_info >= (3, 3): # py3.3+
        if timeout_s==False:
            returnCode, output, is_timeout_reached = _runPY3(command, timeout_s=None, shell=shell)
        else:
            returnCode, output, is_timeout_reached = _runPY3(command, timeout_s=timeout_s, shell=shell)
    else:  # Python 2 and up to 3.2
        if timeout_s==False:
            returnCode, output, is_timeout_reached = _runPY2(command, timeout_s=0, shell=shell)
        else:
            returnCode, output, is_timeout_reached = _runPY2(command, timeout_s=timeout_s, shell=shell)

    return returnCode, output, is_timeout_reached

然后用它如下:

总是将命令作为一个行(它更容易)。你不需要分开它;函数在需要时将分开它。

所以我们可以用这个类似的时间:

a=_run('cmd /c echo 11111 & echo 22222 & calc',3)
for i in a[1].splitlines(): print(i)

或者没有时间:

b=_run('cmd /c echo 11111 & echo 22222 & calc')

更多例子:

b=_run('''wmic nic where 'NetConnectionID="Local Area Connection"' get NetConnectionStatus /value''')
print(b)

c=_run('cmd /C netsh interface ip show address "Local Area Connection"')
print(c)

d=_run('printf "<%s>\n" "{foo}"')
print(d)

你也可以指定Shell=True,但在大多数情况下,这个功能是无用的。我宁愿自己选择我想要的Shell,但这里是,如果你也需要它:

# windows
e=_run('echo 11111 & echo 22222 & calc',3, shell=True)
print(e)
# Cygwin/Linux:
f=_run('printf "<%s>\n" "{foo}"', shell=True)
print(f)

為什麼我沒有使用更簡單的新方法 subprocess.run()?

因为它支持在Python 3.7+,但最后支持的Python版本在Windows XP是3.4. 而且由于这个功能的Timeout论点在Windows中是无用的,它不会杀死执行命令的儿童过程. 如果你使用 capture_output + Timeout论点,它会挂在如果有一个儿童过程仍然运行。

您可以尝试使用 os.system() 运行外部命令。

例子:

import os

try:
  os.system('ls')
  pass
except:
  print("Error running command")
  pass

在示例中,脚本输入OS并试图运行在OS.system()中列出的命令。如果命令失败,那么它将打印“错误运行命令”而没有脚本因错误而停止。

是的,只是如此简单!

下面是一个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.")