【问题标题】:What is the path to the folder my Python script lies in?我的 Python 脚本所在文件夹的路径是什么?
【发布时间】:2023-03-28 06:37:01
【问题描述】:

我希望我的 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。

【问题讨论】:

  • __file__ 给你一个错误,因为你在交互式会话中使用它,没有文件,试图获取文件没有意义
  • @jonatan 我不知道,但这很有意义。谢谢。

标签: python python-3.x path operating-system sys


【解决方案1】:

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

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

【讨论】:

  • 什么时候会比script_location = __file__更好?如果导入,__file__ 仍然可以工作,但这不会
  • 好问题...从来没有真正考虑过。我想唯一真正的区别是__file__ 会给你当前执行文件的位置,不一定是你的主程序......所以这取决于你想弄清楚什么?
猜你喜欢
  • 2015-10-04
  • 2016-07-04
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多