Python 努力将相对路径附加到我的 sys.path

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21259070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:25:46  来源:igfitidea点击:

Struggling to append a relative path to my sys.path

pythonrelative-path

提问by user2564502

So there are a lot of pretty similar questions but none of the answers seems to satisfy what I'm looking for.

所以有很多非常相似的问题,但似乎没有一个答案能满足我的要求。

Essentially I am running a python script using an absolute directory in the command line.
Within this file itself, I want to import a module/file,I currently use an absolute path to do this (sys.path.append(/....).
But I would like to use a relative path, relative to the script itself.
All I seem to be able to do is append a path relative to my present working directory.

本质上,我正在使用命令行中的绝对目录运行 python 脚本。
在此文件本身中,我想导入一个模块/文件,我目前使用绝对路径来执行此操作 ( sys.path.append(/....)
但我想使用相对于脚本本身的相对路径。
我似乎能做的就是附加一个相对于我当前工作目录的路径。

How do I do this?

我该怎么做呢?

回答by olibre

The two below alternate possibilities apply to both Python versions 2 and 3. Choose the way you prefer. All use cases are covered.

以下两种替代可能性适用于 Python 版本 2 和 3。选择您喜欢的方式。涵盖了所有用例。

Example 1

示例 1

main script:      /some/path/foo/foo.py
module to import: /some/path/foo/bar/sub/dir/mymodule.py

Add in foo.py

加入 foo.py

import sys, os
sys.path.append(os.path.join(sys.path[0],'bar','sub','dir'))
from mymodule import MyModule

Example 2

示例 2

main script:      /some/path/work/foo/foo.py
module to import: /some/path/work/bar/mymodule.py

Add in foo.py

加入 foo.py

import sys, os
sys.path.append(os.path.join(os.path.dirname(sys.path[0]),'bar'))
from mymodule import MyModule

Explanations

说明

  • sys.path[0]is /some/path/fooin both examples
  • os.path.join('a','b','c')is more portable than 'a/b/c'
  • os.path.dirname(mydir)is more portable than os.path.join(mydir,'..')
  • sys.path[0]/some/path/foo在这两个例子
  • os.path.join('a','b','c')'a/b/c'
  • os.path.dirname(mydir)os.path.join(mydir,'..')

See also

也可以看看

Documentation about importing modules:

关于导入模块的文档: