Anaconda命令行执行Python脚本时,如何获取脚本所在目录
获取Python脚本所在目录的方法
os.getcwd()返回的是进程的当前工作目录(也就是你执行python命令时所在的目录),这是它的预期行为。要获取脚本本身所在的目录,可以用以下几种方法:
基础方法:利用
__file__属性获取脚本路径,再提取目录import os # 获取脚本的绝对路径 script_abspath = os.path.abspath(__file__) # 提取脚本所在的目录 script_dir = os.path.dirname(script_abspath) print(script_dir)无论你从哪个目录执行脚本,这个方法都会返回脚本实际所在的绝对目录。
处理符号链接场景:如果脚本是符号链接,用
os.path.realpath解析真实路径import os # 解析符号链接,获取脚本的真实绝对路径 real_script_path = os.path.realpath(__file__) script_dir = os.path.dirname(real_script_path) print(script_dir)切换当前工作目录到脚本所在目录:如果你希望后续
os.getcwd()返回脚本目录,可以在脚本开头添加切换目录的代码import os script_dir = os.path.dirname(os.path.abspath(__file__)) # 切换当前工作目录到脚本所在目录 os.chdir(script_dir) # 此时os.getcwd()会返回脚本所在目录 print(os.getcwd())
内容的提问来源于stack exchange,提问作者Tim Kirkwood
相关产品推荐
相关产品推荐

