[英]Call a Python script from a different Python script located at a different location
I have a Python script which is calling a class of another Python script. 我有一个Python脚本正在调用另一个Python脚本的类。 The structure of these two scripts are as follows: 这两个脚本的结构如下:
c:\testing\sample.py
c:\testing\example\demo\projects\module.py
Now inside sample.py
I am calling module.py
as follows: 现在在sample.py
我按如下方式调用module.py
:
from "c:/testing/example/demo/projects/module.py" import module_C
When I execute this portion of sample.py
I get an error There is an error in program
and this error occurs in its first line only. 当我执行sample.py
这一部分时,我得到一个错误程序中There is an error in program
,该错误仅发生在第一行。
How shall I call the module_C
inside sample.py
? 我该module_C
在sample.py
调用module_C
?
the from/import
syntax does not work with files, only with modules. from/import
语法不适用于文件,仅适用于模块。
To achieve what you want, there are 2 possibilities 为了实现您想要的,有2种可能性
first one: turn traversing directories into modules: 第一个:将遍历目录转换为模块:
__init__.py
files in c:/testing/example/demo
, and c:/testing/example/demo/projects
, 在c:/testing/example/demo
和c:/testing/example/demo/projects
创建空的__init__.py
文件, from demo.projects.module import module_C
然后from demo.projects.module import module_C
second one: add path dynamically: 第二个:动态添加路径:
import sys,os
sys.path.add(os.path.join(os.path.dirname(__file__),"demo/projects"))
from module import module_C
knowing where you are running, use current module directory and add the demo/projects
absolute path: it works because the paths have a common prefix) 知道您在哪里运行,请使用当前模块目录并添加demo/projects
绝对路径:它可以工作,因为路径具有公共前缀)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.