Find the path of a shell command

Thomas Passin list1 at tompassin.net
Wed Oct 12 17:28:17 EDT 2022


On 10/12/2022 12:00 AM, Paulo da Silva wrote:
> Hi!
> 
> The simple question: How do I find the full path of a shell command 
> (linux), i.e. how do I obtain the corresponding of, for example,
> "type rm" in command line?
> 
> The reason:
> I have python program that launches a detached rm. It works pretty well 
> until it is invoked by cron! I suspect that for cron we need to specify 
> the full path.
> Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? 
> What about other commands?
> 
> Thanks for any comments/responses.
> Paulo
> 

Python has a command that usually does the job:

import shutil, os
executable_path = shutil.which(exename, os.X_OK)

If you know that the executable you want is on some non-standard path, 
you can or them together:

executable_path = shutil.which(exename, os.X_OK)\
    or shutil.which(exename, os.X_OK, other_path)

Presumably the shutil command uses which behind the scenes, but that 
doesn't matter.

Now you can include this location when you run the executable from 
Python.  If you need to run a system command from a batch file and not 
from Python, you will either need to have the right path in effect when 
the batch file is run, or manually include the full path to the file in 
the batch file.

BTW, on Linux Mint, which is derived from Ubuntu and Debian, rm is at

$ which rm
/bin/rm





More information about the Python-list mailing list