os.path
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
cfg_path = base_path + r'/config.ini'
log_path = base_path + r'/logs'
def get_log_path():
# base_path = os.path.dirname(os.path.abspath(__file__))
print("log_path:",log_path)
return os.path.join(log_path, 'logs')
单独使用os.path.dirname(os.path.abspath(file))
这样使用pyinstaller打包后,当前目录会变成C盘,不是真正的程序路径
上述代码为解决办法
update
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
def get_log_path():
# base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, 'logs')
这段代码主要是在处理文件路径的问题。它使用了Python的os和sys模块来获取程序的当前路径,并构建了配置文件(config.ini)和日志文件夹(logs)的路径。
首先,os.path.dirname(os.path.realpath(sys.argv[0]))
这行代码的作用是获取当前执行脚本的绝对路径。os.path.realpath()
函数返回指定文件的规范路径,消除其中可能存在的符号链接等;os.path.dirname()
函数则返回文件所在的目录。sys.argv[0]
表示当前执行的脚本名。
然后,cfg_path = base_path + r'/config.ini'
这行代码是在当前脚本所在目录下添加’/config.ini’,得到配置文件的完整路径。
同样,log_path = base_path + r'/logs'
这行代码是在当前脚本所在目录下添加’/logs’,得到日志文件夹的完整路径。
最后,get_log_path()
函数的作用是返回日志文件夹的完整路径。这个函数没有参数,直接返回os.path.join(base_path, 'logs')
的结果,即当前脚本所在目录下的’logs’文件夹的完整路径。
关于你提到的单独使用os.path.dirname(os.path.abspath(__file__))
的问题,这是因为__file__
是Python中的一个内置变量,它表示当前执行的脚本的文件名。当你直接运行这个脚本时,__file__
的值就是脚本的文件名,所以os.path.abspath(__file__)
得到的就是脚本的绝对路径。但是,如果你使用pyinstaller等工具将脚本打包成一个可执行文件,那么__file__
的值就会变成可执行文件的路径,而不是脚本的路径。这就是为什么在使用pyinstaller打包后,当前目录会变成C盘,而不是真正的程序路径的原因。