【问题标题】:Calling a command line utility from Python从 Python 调用命令行实用程序
【发布时间】:2018-12-31 14:50:06
【问题描述】:

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

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

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

感谢任何形式的帮助。

没什么,因为我一无所知

【问题讨论】:

    标签: python terminal debian strace


    【解决方案1】:

    您需要使用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

    【讨论】:

      【解决方案2】:

      您可以使用如下命令:

      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] 包含输出。

      【讨论】:

      • 你知道python有一个subprocess模块,完全不需要依赖其他库吗?
      • subprocess.check_output('fortune | grep a', shell=True) 那里,不再依赖你的无用模块。
      【解决方案3】:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-14
        • 1970-01-01
        • 2011-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多