我正在尝试列出我的 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 命令?
compgen是一个内置的 bash 命令,在 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
)最后,所以我更喜欢第一个变体。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)