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


当前回答

我用的是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

其他回答

在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]

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

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

child = pexpect.spawn('ftp 192.168.0.24')

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

child.sendline('anonymous')

child.expect('(?i)password')
import os
os.system("your command")

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

我倾向于与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)

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