Python中os.chdir切换目录时保留路径符号链接的方法问询
问题描述
我当前在路径/nfs/dust/atlas/user/jnitschk/CAF/StatisticTool/Output/frac_100ex_3_smooth_truth下执行脚本,os.getcwd()返回的就是这个路径。现在我需要切换到路径/nfs/dust/atlas/user/jnitschk/CAF/StatisticTool/Output/frac_100ex_3_smooth_truth/Output/ranking_output_Truth_Smooth_ExpSmoothUnblinded_2_100ex_3_frac_obs来执行子进程,但路径里的第二个Output是指向第一个Output的符号链接。执行os.chdir(上述长路径)后,再调用os.getcwd()返回的是解析了符号链接的路径:/nfs/dust/atlas/user/jnitschk/CAF/StatisticTool/Output/ranking_output_Truth_Smooth_ExpSmoothUnblinded_2_100ex_3_frac_obs,请问有没有简便方法让chdir之后保留包含中间符号链接的完整路径?
解决方法
- 手动设置
PWD环境变量:os.chdir会自动解析符号链接更新当前工作目录,你可以在切换目录后,手动把PWD环境变量设为想要的带符号链接的路径,后续调用os.getcwd()就会返回这个路径。示例代码:import os target_path = "/nfs/dust/atlas/user/jnitschk/CAF/StatisticTool/Output/frac_100ex_3_smooth_truth/Output/ranking_output_Truth_Smooth_ExpSmoothUnblinded_2_100ex_3_frac_obs" os.chdir(target_path) # 手动设置PWD为目标路径 os.environ['PWD'] = target_path # 此时os.getcwd()会返回带符号链接的完整路径 print(os.getcwd()) - 执行子进程时直接指定
cwd参数:如果只是为了让子进程在目标路径下运行,无需切换当前脚本的工作目录,直接在subprocess.run()等子进程方法里指定cwd参数为带符号链接的路径即可。当前进程工作目录不变,子进程会在指定路径执行,且子进程内的getcwd()会看到带符号链接的路径(前提是子进程的shell尊重cwd参数的路径形式)。示例代码:import subprocess target_path = "/nfs/dust/atlas/user/jnitschk/CAF/StatisticTool/Output/frac_100ex_3_smooth_truth/Output/ranking_output_Truth_Smooth_ExpSmoothUnblinded_2_100ex_3_frac_obs" # 执行子进程时指定工作路径 subprocess.run(["your_command"], cwd=target_path)
需要注意的是,os.getcwd()的行为依赖于系统和Python实现,手动设置PWD是最直接的方式,但要确保指定的路径真实存在(即使包含符号链接)。
内容的提问来源于stack exchange,提问作者J.N.
相关产品推荐
相关产品推荐

