我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
我写了一封信来处理错误,并重新引导输出和其他东西。
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)
其他回答
我为此写了一本图书馆,shell.py。
它基本上是现在的旋转器和旋转器,它还支持旋转命令,所以你可以在Python中更容易进行连锁命令,所以你可以做这样的事情:
ex('echo hello shell.py') | "awk '{print $2}'"
步骤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 将命令和论点转移到您的系统的阴道. 这很好,因为您实际上可以以这种方式同时运行多个命令,并设置管道和输入/输出重定向。 例如: os.system(“some_command < input_file♰ another_command > output_file”) 但是,虽然这是方便的,您必须手动处理阴道字符的逃避,如空间,和
副过程模块应该是你所使用的。
最后,请注意,对于你通过的所有方法,最终命令将由丝带执行,你负责逃避它。 有严重的安全影响,如果你通过的丝带的任何部分不能完全信任。 例如,如果用户进入某些 / 任何部分的丝带. 如果你不确定,只使用这些方法的连续。
print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()
想象一下,用户输入了一些“我的妈妈不喜欢我&rm -rf /”可以删除整个文件系统。
os.system 是 OK,但类型的日期. 它也不是很安全. 相反,尝试 subprocess. subprocess 不直接呼叫 sh 因此比 os.system 更安全。
在这里获取更多信息
最简单的方式运行任何命令,并获得结果:
from commands import getstatusoutput
try:
return getstatusoutput("ls -ltr")
except Exception, e:
return None
推荐文章
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节