绝对路径还是相对路径

绝对路径还是相对路径

本文介绍了导入模块的最佳实践是什么:绝对路径还是相对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在做一个项目,我将其他 Python 模块的所有路径都定义为绝对路径:

So I was working on a project where I defined all paths to other Python modules as absolute paths:

import sys
sys.path.append('/home/user123/my_project/utilities')
import file_utilities

但是后来我将项目移到了另一个文件夹,这破坏了一切.我必须手动编辑所有路径以说明文件夹更改.

But then I had move the project to a different folder, which broke everything. I had to manually edit all paths to account for the folder change.

我最初使用绝对路径是一个糟糕的选择吗?我最初避免使用相对路径,因为我认为它很快就会变得丑陋:

Is my initial use of absolute paths a bad choice? I initially avoided relative paths because I thought it would quickly become ugly:

import sys
sys.path.append('../../../../utilities')
import file_utilities

最佳做法是什么?

推荐答案

一个方便的解决方案是移动"一个基本路径,即 basepath = "/home/user123/" 到一个变量中并将路径地址为

A handy solution would be to "move" a basepath, i.e. basepath = "/home/user123/" into a variable and address the path as

sys.path.append('{}/my_project/utilities'.format(basepath))

sys.path.append('{}/my_project/utilities'.format(basepath))

那会使相对符号变得丑陋,并为您提供灵活性.

That would ugly relative notation and give you flexibility.

这篇关于导入模块的最佳实践是什么:绝对路径还是相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:14