我的 Python 脚本所在文件夹的路径是什么?

What is the path to the folder my Python script lies in?

我希望我的 Python 脚本也能够被具有其他文件夹设置的人 运行,因此使用对文件夹的引用将 Python 脚本保存到很有意义。

示例:如果我的脚本 "script_1.py" 是 "C:\My Scripts\script_1.py" 的 运行 我想将 "C:\My Scripts" 保存到我可以使用的变量中。

但是,我不能让它太工作。

我导入了 os 和 sys,但是使用 os.path.dirname(__file__)os.path.abspath(__file__) 给出了错误消息:

Traceback (most recent call last):

File "<ipython-input-24-1830932ce69b>", line 1, in <module>
os.path.dirname(__file__)

NameError: name '__file__' is not defined

使用 sys.executable 给我安装 Python 的地址(我想??无论如何它没有给我我要找的东西)。

我也得到了尝试 os.environ['_'] 的建议,但结果是:

Traceback (most recent call last):

File "<ipython-input-26-6c75f8b10c6d>", line 1, in <module>
os.environ['_']

File "D:\Continuum\Anaconda3\lib\os.py", line 669, in __getitem__
   raise KeyError(key) from None

KeyError: '_'

我 运行 顺便说一下,我的代码来自 Windows 10。这是 Python 3.

这将为您提供脚本的位置。

import os
import sys
script_location = os.path.split(os.path.realpath(sys.argv[0]))[0]