我如何在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
其他回答
我倾向于与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)
>>> 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的剩余文档将作为读者的练习留下来。
我会建议使用子过程模块而不是os.system,因为它会让您逃脱,因此更安全。
subprocess.call(['ping', 'localhost'])
subprocess.check_call 是方便的,如果你不想测试返回值。
如果您在命令中不使用用户输入,您可以使用以下操作:
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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从终端/命令行调用VS代码编辑器
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 查看PS命令的全部输出