python - 如何将命令行的输出转换为脚本中的条件?

标签 python linux

<分区>

我试过这个:

import os

if os.system('somecommand') == 'output from command':

    do_something()

但是没有用。我该怎么做?我应该使用什么库?

当我将解决方案与下面的子流程一起使用时,我得到了这个错误代码:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

最佳答案

os.system() 的返回值是进程的退出代码,而不是它输出到标准输入的任何内容。你想使用 subprocess module相反:

import subprocess

if subprocess.check_output('somecommand') == 'output from command':

关于python - 如何将命令行的输出转换为脚本中的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331684/

相关文章:

C++ 代码库从 MFC 重写为 *nix

python - pyinotify 疑似线程问题

python - 在 sklearn.feature_selection 之后过滤 DataFrame

python - CherryPy + Jinja,在哪里初始化环境

python - 如何在测试中遵循 Pyramid 重定向?

python - ssh 使用 Python 限制命令

python - SQLAlchemy 表达式语言 : how to join table with subquery?

python - 如何获取kivy中动画的对象?

linux - 使用 bash 脚本使用 valgrind 检查内存

linux - 检查文件是否存在 bash 不工作