Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Python command used to run the current Python script

Tags:

python

If I run a Python script, foo.py with

$ python3.6 foo.py

sys.argv will return ['foo.py']. But I want something that will return the name of the command used to launch the script. In this case 'python3.6'.

Is this possible?

like image 733
Mike S Avatar asked Jul 24 '26 11:07

Mike S


1 Answers

It sounds like you’re looking for sys.executable:

A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, sys.executable will be an empty string or None.

This is commonly used for things like running another Python script via subprocess.run([sys.executable, 'spam.py', 'arg').

This gives you the absolute path to the Python interpreter. If you want just the name, use os.path.basename(sys.executable).

Keep in mind that it’s always possible that, say, /usr/local/bin/python3.6 is actually just a symlink or even a shim launcher for something named, say, /opt/local/python3.6/bin/python3, in which case you might get the latter path, and basenaming it would then give you python3, but then running python3 might run a different python3 that’s higher on the path. Using the absolute path, you won’t have that problem.

like image 174
abarnert Avatar answered Jul 27 '26 03:07

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!