Python -m switch to run module inside package

戏子无情 提交于 2020-01-24 19:36:26

问题


I am reading this article.

I am wondering why the below statement from the article is correct? As I can use the solution 1 - that is - python -m packA.a2 and it works fine.

To give you some context, Solution 1 says:

Use absolute imports rooted at the test/ directory (i.e. middle column in the table above). This guarantees that running start.py directly will always work. In order to run a2.py directly, run it as an imported module instead of as a script:

  1. change directories to test/ in the console
  2. python -m packA.a2

But in Case 3 the author says:

sys.path could change (take 2)

A harder problem to deal with is the following example. Suppose a2.py never needs to be run directly, but it is imported by both start.py and a1.py which are run directly.

In this case, using Solution 1 described above won’t work. However, the other solutions are still valid.

But I tried this and got this to work using python -m packA.a1


回答1:


I asked you to create this question but unfortunately don't have an answer. I thought you were the one who created the definitive guide to python imports and would be able to provide a detailed example.

The problem with the article is that it's not clear what he means by his case. We've created what we think he means in both python2 and python3 and they work

Maybe Christopher Yeh will see this question some day and clear up the mystery, possibly improving his definitive guide in the process.



来源:https://stackoverflow.com/questions/58577767/python-m-switch-to-run-module-inside-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!