【问题标题】:Subprocess library won't execute compgen子进程库不会执行 compgen
【发布时间】:2014-06-26 08:52:03
【问题描述】:

我正在尝试列出我的 linux (Lubuntu) 机器上可用的每个命令。我想在 Python 中进一步使用该列表。通常要在控制台中列出命令,我会编写“compgen -c”并将结果打印到标准输出。

我想使用 Python 子进程库执行该命令,但它给了我一个错误,我不知道为什么。

代码如下:

   #!/usr/bin/python

   import subprocess

   #get list of available linux commands
   l_commands = subprocess.Popen(['compgen', '-c'])

   print l_commands

这是我得到的错误:

   Traceback (most recent call last):
     File "commands.py", line 6, in <module>
       l_commands = subprocess.Popen(['compgen', '-c'])
     File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
       errread, errwrite)
     File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
       raise child_exception
   OSError: [Errno 2] No such file or directory

我被困住了。你们能帮我解决这个问题吗?如何使用子进程执行 compgen 命令?

【问题讨论】:

    标签: linux python-2.7 subprocess compgen


    【解决方案1】:

    compgen is a builtin bash command,在shell中运行:

    from subprocess import check_output
    
    output = check_output('compgen -c', shell=True, executable='/bin/bash')
    commands = output.splitlines()
    

    你也可以这样写:

    output = check_output(['/bin/bash', '-c', 'compgen -c'])
    

    但它将基本部分 (compgen) 放在最后,所以我更喜欢第一个变体。

    【讨论】:

    • 感谢塞巴斯蒂安,这非常有效。我还根据答案here 找到了另一个解决方案。你也可以像这样执行命令:l_commands = Popen(["bash -c 'compgen -c'"], shell = True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    • @user3573032:不要混合使用列表参数和shell=True。如果您在命令中使用bashshell=True 也是多余的。我已经更新了答案
    【解决方案2】:

    我不确定 compgen 是什么,但该路径必须是绝对的。当我使用子进程时,我会拼出确切的页面/absolute/path/to/compgen

    【讨论】:

    • 这很奇怪,但是当我尝试通过 'which compgen' 定位 compgen 时,输出为空。但是当我在终端中运行“compgen -c”时,它会给出可用命令的列表。
    • @user3573032: compgen 可能是一个 shell 函数。在 shell 中运行:type compgen
    • 我运行type compgen,它确实是一个内置的shell。知道了这一点,有什么办法可以用子流程执行吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多