2021年5月3日星期一

How can I perform a dynamic import inside a packaged library in python?

I'm writing a library that will be packaged and available to install via pip on Pypi. I have a few script targets in my setup.py

"console_scripts": [      "mlab=install.make_lab:mlab",      "rlab=install.run_lab:rlab",      "clab=install.clear_lab:clab"  ]  

These are primarily intended as programmer tools that supplement the main library.

The mlab command creates a directory structure as follows inside the users project:

laboratory/            |- lab.py            |- labmain.py  

Inside of labmain.py I have a main() function.

import laboratory.lab as lab    def main():      print("I am the main!")      print(lab.name)    

I would like to attach this main method to my shell commands.

I have tried this:

import os    def rlab():      """      This shell command is used to run a lab.      """      lab_dir_path = os.path.join(os.getcwd(), "laboratory")      if not os.path.isdir(lab_dir_path):          print("No lab exists... run the mlab command to make a lab.")      main = __import__("laboratory.labmain")      os.chdir("laboratory")      main.main()    

As well as a direct import using from laboratory import labmain

I continue to get a ModuleNotFoundError.

It is important to note that the rlab function is being packaged and then uploaded via twine to testpypi. I am then installing the package in a separate project, which contains the lab structure after I run the mlab shell command. Everything seems to work fine, until it's packaged.

https://stackoverflow.com/questions/67377990/how-can-i-perform-a-dynamic-import-inside-a-packaged-library-in-python May 04, 2021 at 10:22AM

没有评论:

发表评论