简体   繁体   English

从位于不同位置的其他Python脚本调用Python脚本

[英]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_Csample.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: 第一个:将遍历目录转换为模块:

  • create empty __init__.py files in c:/testing/example/demo , and c:/testing/example/demo/projects , c:/testing/example/democ:/testing/example/demo/projects创建空的__init__.py文件,
  • then 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.

相关问题 从 shell 脚本调用位于自定义位置的 python 脚本的 python function - From shell script call a python function of python script located at custom location Python 脚本调用不同的 Python 脚本,然后从辅助脚本将字符串/结果带到主脚本 - Python Script call a different python script, then, from secondary script bring an string/result to main script Python 如果从 Windows 上的不同位置运行 as.exe,则脚本的位置 - Python location of script if run as .exe from different place on Windows 如果从另一个位置运行python脚本,则参考其中的位置 - Reference where a python script is located if being run from another location 从不同的路径调用 python 脚本并更改路径 - call a python script from a different path and change path python:从不同目录中的脚本调用类并获取函数 - python: call a class from a script in a different directory and get function 如何从不同的脚本调用方法? (Python) - How do I call a method from a different script? (Python) 如何在不同的 Python 脚本中调用 Scrapy Spider - How to call a Scrapy Spider in a different Python Script Python:当位于与主脚本不同的文件夹中时,如何设置 cx_Freeze 脚本? - Python: How to setup cx_Freeze script when located in different folder than main script? 如何从python脚本调用具有不同管道的不同项目的Spiders? - How do I call spiders from different projects with different pipelines from a python script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM