如果我运行 Python 脚本,foo.py
和
$ python3.6 foo.py
sys.argv
将返回 ['foo.py']
.但是我想要一些可以返回用于启动脚本的命令的名称的东西。在这种情况下 'python3.6'
.这可能吗?
最佳答案
听起来您正在寻找 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 orNone
.
这通常用于通过
subprocess.run([sys.executable, 'spam.py', 'arg')
运行另一个 Python 脚本之类的事情。 .这为您提供了 Python 解释器的绝对路径。如果您只想要名称,请使用
os.path.basename(sys.executable)
.请记住,总是可能的,例如
/usr/local/bin/python3.6
实际上只是一个符号链接(symbolic link),甚至是一个名为 /opt/local/python3.6/bin/python3
的东西的 shim 启动器。 ,在这种情况下,您可能会得到后一种路径,然后对其进行基础命名将为您提供 python3
,然后运行 python3
可能会运行不同的 python3
那是更高的路径。使用绝对路径,你不会有这个问题。
关于python - 获取用于运行当前 Python 脚本的 Python 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51996412/