问题描述
我正在尝试在Linux(Lubuntu)机器上提供每个命令的列表.我想在Python中进一步处理该列表.通常,要在控制台中列出命令,我会写"compgen -c",它将结果打印到stdout.
I am trying to make list of every command available on my linux (Lubuntu) machine. I would like to further work with that list in Python. Normally to list the commands in the console I would write "compgen -c" and it would print the results to stdout.
我想使用Python子进程库执行该命令,但它给了我一个错误,我不知道为什么.
I would like to execute that command using Python subprocess library but it gives me an error and I don't know why.
代码如下:
#!/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命令?
I'm stuck. Could you guys help me with this? How to I execute the compgen command using subprocess?
推荐答案
compgen
是内置的bash命令,在shell中运行它:
compgen
is a builtin bash command, run it in the 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
)放在最后,所以我更喜欢第一个变体.
But it puts the essential part (compgen
) last, so I prefer the first variant.
这篇关于子流程库将不会执行compgen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!