【问题标题】:Taking the results of a bash command and using it in python获取 bash 命令的结果并在 python 中使用它
【发布时间】:2011-08-10 08:10:06
【问题描述】:

我正在尝试在 python 中编写代码,该代码将从顶部获取一些信息并将其放入文件中。 我只想写下应用程序的名称并生成文件。我遇到的问题是我无法获得 pidof 命令的输出,因此我可以在 python 中使用它。我的代码如下所示:

import os

a = input('Name of the application')
val=os.system('pidof ' + str(a)) 
os.system('top -d 30 | grep' + str(val) + '> test.txt')
os.system('awk '{print $10, $11}' test.txt > test2.txt')

问题是 val 总是有 0 但命令返回我想要的 pid。任何输入都会很棒。

【问题讨论】:

  • 你有应用程序的名称,你想要...什么?将有关此应用程序的内容写入文件?

标签: python bash operating-system command


【解决方案1】:

首先,不鼓励使用input(),因为它希望用户输入有效的 Python 表达式。请改用raw_input()

app = raw_input('Name of the application: ')

接下来,system('pidof') 的返回值不是 PID,而是pidof 命令的退出代码,即成功时为零,失败时非零。你想要capture the outputpidof

import subprocess

# Python 2.7 only
pid = int(subprocess.check_output(['pidof', app]))

# Python 2.4+
pid = int(subprocess.Popen(['pidof', app], stdout=subprocess.PIPE).communicate()[0])

# Older (deprecated)
pid = int(os.popen('pidof ' + app).read())

下一行在grep 之后缺少一个空格,会导致类似grep1234 的命令。使用字符串格式化操作符% 会更容易发现:

os.system('top -d 30 | grep %d > test.txt' % (pid))

第三行被错误地引用,应该导致语法错误。注意单引号内的单引号。

os.system("awk '{print $10, $11}' test.txt > test2.txt")

【讨论】:

  • 这就是你想要的答案。如果您愿意,可以将其抽象为一个函数。但是请注意,您可能需要调用 .strip() 来删除输出中的换行符: .communicate()[0].strip() - 在这种情况下您不需要这样做,因为 int('12\n ')==12
  • 感谢您提供的解决方案。你帮了我很多,再次感谢你的快速反应。我正在使用 python3 和 raw_input 它不支持或者我不知道是否有新的形式。
  • raw_input在python3中的等价物是input,没有2.X的等价物
【解决方案2】:

建议你使用子进程模块,而不是os.system:http://docs.python.org/library/subprocess.html#module-subprocess

使用该模块,您可以与 shell 进行通信(输入和输出)。该文档解释了如何使用它的详细信息。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多