python - 获取用于运行当前 Python 脚本的 Python 命令

标签 python

如果我运行 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 or None.



这通常用于通过 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/

相关文章:

python - 如何使用 boto3 从 s3 获取最后修改的文件名

python - 安装 Twitter Python 模块

python - flask 和 wtf - 如何为字段指定标记属性?

python - 为什么 Python 在打印回溯时从当前目录读取?

Python:动态导入模块内容

python - Arduino 和 pySerial 的问题

python - OpenCV安装: deprecation error

python - Mongo引擎和服务器状态

python - Pandas 数据框中列的输出从 float 到货币(负值)

python - 用另一个系列过滤 Pandas 数据框