如何从脚本中找到运行脚本的Python的目录?

2024-05-23 09:34:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从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)

Tags: 代码fromimport目录脚本modsossys
3条回答

试试这个:

import os
os.path.dirname(__file__)

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

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

print "hi"

无效。打印现在是一项功能。

print("hi")

有效。你需要括号。

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

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

或者,如果希望调用脚本的目录:

import os
path = os.getcwd()

docs

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.

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

这应该有效:

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

相关问题 更多 >

    热门问题