【问题标题】:subprocess.run() doesn't return any output [duplicate]subprocess.run() 不返回任何输出[重复]
【发布时间】:2021-02-10 11:27:30
【问题描述】:

我不知道为什么我的代码没有返回任何输出。我正在运行 python 3.8

bash_command = ['compgen', '-c']
process = subprocess.run(bash_command,
                         check=True,
                         text=True,
                         shell=True,
                         executable='/bin/bash',
                         capture_output=True
                         )

software_list = process.stdout.split('\n')
print(software_list)

打印给我一个空列表:['']

编辑:

  1. compgen 是 bash 命令,它列出了所有可用的命令,包括 PATH 中可用的内置程序和已安装程序
  2. 我的机器上安装了 compgen

【问题讨论】:

  • 请在software_list = process.stdout.split('\n')之前添加print(process)并写下它的输出内容。
  • print(repr(process)) 显示什么?
  • print(process) 和 print(repr(process)) 都返回: CompletedProcess(args=['compgen', '-c'], returncode=0, stdout='', stderr=' ')
  • 这能回答你的问题吗? Subprocess library won't execute compgen

标签: python python-3.x subprocess


【解决方案1】:

当您运行指定shell=True 的程序时,命令参数可以是单个字符串而不是字符串列表。这是一个需要为单个字符串的实例:

import subprocess


bash_command = 'compgen -c' # single string
process = subprocess.run(bash_command,
                         check=True,
                         text=True,
                         shell=True,
                         executable='/bin/bash',
                         capture_output=True
                         )

software_list = process.stdout.split('\n')
print(software_list)

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2012-02-04
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多