When dealing with an external program in Python, I wanted to check if the external program existed before execution, so I checked it. You can also check for run-time errors, but before that, you just want to check that it's available. Or you can use it when you want to find out the path where the program is installed.
The external program is supposed to be executed by subprocess.Popen
etc.
I tried Python versions 3.5.1 and 2.7.11.
Use the which function of the shutil module.
Returns the path to the command if the command is executable, or None
if not found.
import shutil
print(shutil.which('ls')) # > '/bin/ls'
print(shutil.which('ssss')) # > None
shutil.which
is not backported and cannot be used in Python 2.7.
I think it's better to move to 3.5 or higher immediately, but I think that some people can't do it, so I'll show you how to use it with old Python.
You can do the same with shutil.which
with distutils.spawn.find_executable
.
http://stackoverflow.com/questions/5226958/which-equivalent-function-in-python
import distutils.spawn
print(distutils.span.find_executabl('ls')) # > '/bin/ls'
print(distutils.span.find_executabl('ssss')) # > None
If you don't know this, you can't find it ... This method can be used in 3 series, but distutils was treated as a minor and there was no documentation. http://docs.python.jp/3/library/distutils.html
The trap point is
-- shutil
is singular, but distutils
is plural
--If you only use ʻimport distutils, the
spawn module will not be imported, so you need to ʻimport distuils.spawn
or from distutils import spawn
Etc.
Recommended Posts