import os
wd = os.getcwd() # save current working directory
os.chdir('path/to/dir_one') # change to directory containing main.py
from main import items # import your stuff
os.chdir(wd) # change back to directory containing sub.py
# script.py (updated)
if __name__ == '__main__' and __package__ is None:
__package__ = 'test_dir.sub1'
import test_dir # needed to suppress SystemError I'm not sure why...
from .. import main
from ..sub2 import module
def entry_point():
module.run_func()
main.func_in_main()
if __name__ == '__main__':
entry_point()
现在让我们再次尝试直接运行这个程序:
$ python test_package/test_dir/sub1/script.py
test_package/test_dir/sub1/script.py:4: RuntimeWarning: Parent module 'test_dir.sub1' not found while handling absolute import
import test_dir
Hello from script in sub2.py!
Hello from main.py!
在你的文件
sub.py
中,你可以做如下的事情在使用您的项目窗体主。在
编辑:在您的特定情况下,
'path/to/dir_one'
只需向上一个目录,即'..'
你有几个选择。在
最好的选择是将包与使用包的脚本分开。查看一下^{} 中的setuptools。将setuptools指向包中的函数,它将创建一个脚本来调用它。漂亮。。。在
为了解决这个问题,我设置了以下包结构:
我确保
test_dir
可以通过PYTHONPATH
进行访问。在这些脚本都非常简单(只是打印一些东西):
^{pr2}$现在,如果我直接运行这个会怎么样?在
嗯。。。糟糕(这是我试图在你最初的问题的评论中描述的情况)。顺便说一下,不管我当前的工作目录是什么。。。但是,在我的文件系统的任何地方,我可以使用
-m
标志1来运行它:你好!我们只需要指定模块路径,然后就成了golden(记住,
test_dir
必须通过python路径可以访问到它才能工作)。好吧,但是如果我们真的想调用脚本而不是使用模块路径呢?如果是这种情况,我们可以在导入之前修改__package__
变量:现在让我们再次尝试直接运行这个程序:
我们仍然得到一个
RuntimeWarning
,但运行正常。有关详细信息,请查看PEP-0366。在1一般来说,我都是从包外部运行的(高于
test_dir
的一个级别),但是如果我从包的内部运行它,那么这些示例也可以工作。使用-m
您总是指定模块的完整路径(test_dir.sub1.script
),没有它,您只需指定文件的相对或绝对路径)相关问题 更多 >
编程相关推荐