Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subprocess library won't execute compgen

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.

I would like to execute that command using Python subprocess library but it gives me an error and I don't know why.

Here is the code:

   #!/usr/bin/python

   import subprocess

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

   print l_commands

Here is the error I'm getting:

   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

I'm stuck. Could you guys help me with this? How to I execute the compgen command using subprocess?

like image 713
xlogic Avatar asked Sep 01 '26 01:09

xlogic


1 Answers

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()

You could also write it as:

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

But it puts the essential part (compgen) last, so I prefer the first variant.

like image 107
jfs Avatar answered Sep 04 '26 16:09

jfs