Mike S
Mike S

Reputation: 1603

Get Python command used to run the current Python script

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?

Upvotes: 7

Views: 2606

Answers (1)

abarnert
abarnert

Reputation: 365707

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.

Upvotes: 11

Related Questions