从Python调用命令行实用程序

时间:2018-12-31 14:50:07

标签: python terminal debian strace

我目前正在尝试利用strace自动跟踪programm的系统调用。然后,为了解析和处理获得的数据,我想使用Python脚本。

我现在想知道,如何从Python调用strace? Strace通常是通过命令行调用的,我不知道可以利用strace编译的任何C库。

通过Python模拟通过命令行访问的一般方法是什么? 或者:是否有任何与strace类似的工具是用Python原生编写的?

我很感谢您的帮助。

没事,因为我很笨

3 个答案:

答案 0 :(得分:2)

您需要使用subprocess模块。

它有check_output可以读取输出并将其放入变量中,还有check_call可以检查退出代码。

如果要运行Shell脚本,可以将其全部写入字符串并设置shell=True,否则只需将参数作为字符串放入列表中即可。

import subprocess
# Single process
subprocess.check_output(['fortune', '-m', 'ciao'])
# Run it in a shell
subprocess.check_output('fortune | grep a', shell=True)

请记住,如果您在Shell中运行内容,则无法正确转义并允许用户数据进入字符串,则很容易造成安全漏洞。最好不要使用shell=True

答案 1 :(得分:1)

您可以使用以下命令:

import commands
cmd = "strace command"
result = commands.getstatusoutput(cmd)
if result[0] == 0:
   print result[1]
else:
   print "Something went wrong executing your command"

result[0]包含返回码,result[1]包含输出。

答案 2 :(得分:0)

Python 2和Python 3(3.5版之前)

只需执行:

subprocess.call(["strace", "command"])

执行并返回输出以进行处理:

output = subprocess.check_output(["strace", "command"])

参考:https://docs.python.org/2/library/subprocess.html

Python 3.5 +

output = subprocess.run(["strace", "command"], caputure_output=True)

参考:https://docs.python.org/3.7/library/subprocess.html#subprocess.run

相关问题