Reputation: 815
I have the following code which i am using to check if the program class-dump exists on a system. The program only returns a blank.
cmd = ["which","class-dump"]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
print process.stdout.read()
This code always returns a blank. Technically it should work right ?
Upvotes: 1
Views: 572
Reputation: 19367
This code does the same thing as the shell which
command programatically, except that it does not "find" symbolic links. To support that, you can enhance the isx
function.
import os.path, itertools
isx = lambda program: lambda folder: (lambda p: \
os.access(p, os.X_OK) and os.path.isfile(p))(os.path.join(folder, program))
def which(program):
try:
return itertools.ifilter(isx(program), os.environ['PATH'].split(':')).next()
except StopIteration:
raise ValueError, 'no executable file named %s found in search path' % (program,)
Example use:
>>> which('ls')
'/bin'
>>> which('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in which
ValueError: no executable file named foo found in search path
Upvotes: 0
Reputation: 4224
I tried the following on my machine and its working perfectly.
import subprocess
cmd = ["which","java"]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
print process.communicate()
this is the output
('/usr/bin/java\n', None)
Upvotes: 2
Reputation: 2409
which
is a shell built-in. You need to pass shell=True
to the Popen.
Upvotes: 1
Reputation: 80801
Hmmm, it looks like the class-dump does not exists (in the PATH used by your python interpreter)
Upvotes: 0
Reputation: 96897
Does it work if you use communicate
instead? See this warning:
Warning
Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
Also, is it possible that your script runs under another PATH
than your shell? Dump os.environ["PATH"]
and check.
Upvotes: 0