【问题标题】:How can i retrieve the output shown on my command line using python?如何使用 python 检索命令行上显示的输出?
【发布时间】:2019-02-16 19:37:46
【问题描述】:

使用 ubuntu 16.04 我想要的是使用 python 检索终端上的输出,我确实参考了这两个链接: How can I get terminal output in python?

Running shell command from Python and capturing the output

但作为 python 的初学者,我无法让它工作,我想要输出的原始代码:

for element in my_images:
    os.system('you-get -o videos ' + element)

我的代码是如何变成的:

for element in my_images:
    # value = os.system('you-get -o videos ' + element)
    output = subprocess.Popen(os.system('you-get -o videos ' + element), stdout=subprocess.PIPE).communicate()[0]
    print(output)

但它没有工作我得到这个错误

Traceback (most recent call last):
  File "main_twitter.py", line 29, in <module>
    output = subprocess.Popen(os.system('you-get -o videos ' + element), stdout=subprocess.PIPE).communicate()[0]
  File "/usr/local/lib/python3.6/subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "/usr/local/lib/python3.6/subprocess.py", line 1220, in _execute_child
    args = list(args)
TypeError: 'int' object is not iterable

【问题讨论】:

  • 当你使用subprocess 时,你不应该使用os.system 命令,它返回一个整数。您应该按原样运行命令。

标签: python python-3.x shell subprocess


【解决方案1】:

您应该直接使用命令和参数调用Popen 的构造函数。调用os.system 将执行命令并返回退出代码,这不是您想要传递给Popen 的代码:

output = subprocess.Popen('you-get -o videos ' + element, shell=True, stdout=subprocess.PIPE).communicate()[0]

【讨论】:

  • 当我打印输出时,我只是得到 b' ',甚至引号内也没有任何内容。
  • 您的you-get 命令可能有错误。您应该检查communicate 方法返回的元组的第二项中的错误消息(将[0] 更改为[1])。
  • 这是正确的一些崩溃的其他工作,但我得到 None 对于现在工作和崩溃的两者。
  • 对于那些我确实得到无法理解的输出的工作,我尝试使用 print(output).decode('utf-8') 进行解码,但它没有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 2017-03-25
  • 1970-01-01
  • 2020-12-15
相关资源
最近更新 更多