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


当前回答

在 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

其他回答

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

from sultan.api import Sultan

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

从 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

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

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

典型的实施:

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()一样行事。

import subprocess

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

网上尝试