Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在模块上运行Python,并从另一个目录进行相对导入_Python - Fatal编程技术网

在模块上运行Python,并从另一个目录进行相对导入

在模块上运行Python,并从另一个目录进行相对导入,python,Python,假设在/path/to/foo下我有一个带有python模块的包: /path/to/foo: | my_package | __init__.py | my_module.py | my_other_package | __init__.py | my_oth

假设在
/path/to/foo
下我有一个带有python模块的包:

/path/to/foo:
           | my_package
                        | __init__.py
                        | my_module.py

           | my_other_package
                        | __init__.py
                        | my_other_module.py
文件
my_module.py
相对导入
my_other_module.py
,如下所示:

  from ..my_other_package import my_other_module
我理解我可以从shell中执行以下操作:

> cd /path/to/foo
> python -m my_package.my_module
但是如果我不想更改当前目录呢?有没有办法从shell运行我的模块而不必更改PYTHONPATH

我尝试了以下方法:

python -m /path/to/foo/my_package.my_module
但那没用。我得到:
不支持按文件名导入

获取相对路径:

base_path=os.path.abspath(“../my_other_package/”)#或任何相关目录

将其附加到系统路径(仅临时,将在执行后删除):
sys.path.append(基本路径)

在该路径中导入所需的文件:
导入我的其他模块.py

我相信您可能需要一个名为
\uuuu init\uuuuuuuuupy
(其中没有任何内容)的文件,如果您想将该文件导入为
导入目录.file
(如果我错了,请纠正我)


线程显示了其他方法。

您是否尝试过使用从my_package到my_other_package/my_other_module.py的符号链接?您是否也尝试过在
/path/to/foo
中添加
\u init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?如果
foo
本身不是一个软件包,我认为你无法做到这一点。谢谢。我已经读到篡改
sys.path
不是一个好主意,但我想这是我能做的最好的了。。