简体   繁体   English

从另一个目录运行Python脚本

[英]Running Python a script from another directory

First, imagine the following file structure: 首先,假设以下文件结构:

project-dir
|_ 
   package1
   |_ 
      __init__.py
      module1.py
      module2.py

And the following script contents: 以及以下脚本内容:

module2.py: module2.py:

def func_module2():
    print('func_module2 run')

module1.py: module1.py:

from package1 import module2

module2.func_module2()

The following command creates an error when executed from the project-dir: 从项目目录执行以下命令会产生错误:

python package1/module1.py

Error: 错误:

Traceback (most recent call last):
  File "./package1/module1.py", line 1, in <module>
    from package1 import module2
ImportError: No module named 'package1'

Why is this happening and how is it possible to run a Python script from another directory? 为什么会发生这种情况,又有可能从另一个目录运行Python脚本吗?

Python 3.5.2 Python 3.5.2

Your problem seem to be that module1.py and module2.py both lives in the same package. 您的问题似乎是module1.pymodule2.py都位于同一包中。 From module1.py you won't find module2.py in another package. module1.py您不会在另一个软件包中找到module2.py Instead try: 而是尝试:

import module2

module2.func_module()

Trying that I get: 尝试我得到:

> python package1/module1.py
func_module2 run

However if you want it to work as a package too (or using newer versions of python), you must istead use 但是,如果您希望它也作为软件包工作(或使用新版本的python),则必须使用

from . import module2

module2.func_module()

but that will make python package1/module1.py not work since it will not be run as part of a package. 但这会使python package1/module1.py无法工作,因为它不会作为程序包的一部分运行。 Instead you can use 相反,您可以使用

> python -m package1.module1
func_module2 run

module2 and module1 are under the same namespace. module2module1在同一名称空间下。 So it MUST be: 因此它必须是:

# module1.py
import module2

module2.func_module2()

from package1 import module2 is valid only in the following context/namespace: from package1 import module2仅在以下上下文/名称空间中有效:

在此处输入图片说明

Exemple: 例:

# test.py
from package1 import module2

module2.func_module2()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM