【问题标题】:How do I find directory of the Python running script from inside the script?如何从脚本内部找到 Python 运行脚本的目录?
【发布时间】:2013-10-19 19:27:51
【问题描述】:

如何从 Python [3.3] 中找到正在运行的 Python 脚本的目录? 我已经尝试过以下建议:How can I find script's directory with Python?,但我得到“无效语法”并指向“os”(我确实导入了 os)。

我得到的最接近答案的是: sys.argv[0] ,但它仍然包含文件名,所以我不能使用它。有没有其他办法?

注意: 我对 Python 还很陌生。

这是我到目前为止编写的一些代码(它说 rundir = sys.argv[0] 的部分是建议的代码所在的位置):

import pygame
from pygame.locals import *
import os, sys
import time
pygame.init()

import statuscheck
print("Completed program status check.")

import mods.modlist
print("Loaded all mods..")

print("Completed loading")

sys.dont_write_bytecode = True

rundir = sys.argv[0]

print("Running from" + rundir)

【问题讨论】:

  • 你能发布你的确切代码和你得到的确切错误吗?您链接的答案听起来应该适合您。

标签: python directory


【解决方案1】:

试试这个:

import os
os.path.dirname(__file__)

__file__ 获取您所在文件的名称。dirname 函数获取文件所在的目录。

语法错误可能与打印语句有关。在 python 3.x 中

print "hi"

无效。打印现在是一个函数。

print("hi")

有效。你需要括号。

【讨论】:

    【解决方案2】:

    获取包含您正在运行的模块的目录:

    import os
    path = os.path.dirname(os.path.realpath(__file__))
    

    或者如果你想要调用脚本的目录:

    import os
    path = os.getcwd()
    

    来自docs

    __file__ 是加载模块的文件的路径名,如果它是从文件加载的。

    根据脚本的调用方式,这可能是来自os.getcwd() 的相对路径,因此os.path.realpath(__file__) 会将其转换为绝对路径(或者什么都不做,因为__file__ 已经是绝对路径)。然后os.path.dirname() 将通过剥离文件名返回完整目录。

    【讨论】:

    • 你可以通过Path(__file__).resolve().parent得到一个Path对象。
    【解决方案3】:

    这应该可行:

    import os,sys
    print(os.path.dirname(os.path.realpath(sys.argv[0])))
    

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 2014-09-06
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多