简体   繁体   English

在python3中的运行时从动态路径导入固定模块

[英]Importing a fixed module from a dynamic path at runtime in python3

I have searched around and not found a solution to this particular Python3 problem. 我四处搜寻,但未找到解决此特定Python3问题的解决方案。 Perhaps it's the keywords I'm using, or it could be just a special use case. 也许是我正在使用的关键字,或者可能只是一个特殊的用例。 In the event that my problem is the latter, here is my question: 如果我的问题是后者,这是我的问题:

I'm developing a python (3) script which needs to use a python module which has been compiled locally in the user's home directory. 我正在开发一个python(3)脚本,该脚本需要使用已在用户主目录中本地编译的python模块。 I do not have anything so fancy as a configure script to configure this path for the user as an automated process. 作为配置脚本,我没有什么花哨的东西可以将用户的路径配置为自动化过程。 I want to pass the path to the python module to the script at runtime as a command line argument, and then dynamically load that module. 我想在运行时将python模块的路径作为命令行参数传递给脚本,然后动态加载该模块。 For example, I will call: 例如,我将呼叫:

$ myscript.py --modpath /home/user/path/to/ModuleSource

and then in my code call something like the following when I parse the command line arguments: 然后在我分析命令行参数时,在我的代码中调用如下内容:

import sys
sys.path.append(localModulePath)
import GlobalModuleName

The problem is that in the static code for my script which uses the module methods, the actual module cannot be resolved until runtime when the definitions for the module are passed to my script. 问题在于,在使用模块方法的脚本的静态代码中,只有在运行时将模块的定义传递给脚本时,才能解析实际的模块。 That is, if I have python code like the following 也就是说,如果我有如下的python代码

GlobalModuleName.moduleFunc()

I get runtime errors of " NameError: name 'GlobalModuleName' is not defined ". 我收到“ NameError:名称'GlobalModuleName'未定义 ”的运行时错误。

How do I get this configuration to work without generating an error? 如何使该配置正常工作而不产生错误? I am certain that the code that will use the dynamic definitions of the module is correct. 我确定将使用模块的动态定义的代码是正确的。 Thanks for the pointers in advance. 感谢您提前的指示。

This worked perfectly for me 这对我来说很完美

module1.py import os import sys module1.py import os导入系统

def func1():
    print("Executed func1 of module1")

main.py main.py

import sys

pathPassed=sys.argv[1]
sys.path.append(pathPassed)
import module1
module1.func1()

Execution 执行

 python main.py ThePathformodule1.py

Executed func1 of module1

The only thing you have to take care is that the import statement should be after the sys.path.append 您唯一需要注意的是, import语句应该在sys.path.append

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

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