简体   繁体   中英

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. 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. 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. 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

GlobalModuleName.moduleFunc()

I get runtime errors of " NameError: name 'GlobalModuleName' is not defined ".

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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