Not going to do any good if it’s not on the PATH in the first place:

https://docs.python.org/3/library/shutil.html

shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None)
Return the path to an executable which would be run if the given cmd was 
called. If no cmd would be called, return None.
mode is a permission mask passed to 
os.access()<https://docs.python.org/3/library/os.html#os.access>, by default 
determining if the file exists and executable.
When no path is specified, the results of 
os.environ()<https://docs.python.org/3/library/os.html#os.environ> are used, 
returning either the “PATH” value or a fallback of 
os.defpath<https://docs.python.org/3/library/os.html#os.defpath>.


From: Python-list <python-list-bounces+gweatherby=uchc....@python.org> on 
behalf of Thomas Passin <li...@tompassin.net>
Date: Wednesday, October 12, 2022 at 5:39 PM
To: python-list@python.org <python-list@python.org>
Subject: Re: Find the path of a shell command
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

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



--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lyWawGnR8ddR5pCSS5bC09WInoHss_eleSRXxsjbIL_ndHz2TPW246oagSmaBVekZyVjzO7zKsGqN9NpLtM$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lyWawGnR8ddR5pCSS5bC09WInoHss_eleSRXxsjbIL_ndHz2TPW246oagSmaBVekZyVjzO7zKsGqN9NpLtM$>
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to