简体   繁体   中英

How to make all my imports in a separete setup.py file then importing this file in main.py?

I'm trying to make a setup script that will install needed python modules on machines that don't have it. so going with the recommended way of installing packages this is my setup.py

import subprocess
import sys
import importlib

required_packages = ["cryptography.fernet", "os", "pip"]
for package in required_packages:
    try:
        importlib.import_module(package)
        print("Imported {} successfully".format(package))
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        print("Installed {} successfully".format(package))

and main.py as :

import setup
os.walk(".")   # cause an error

This way I have control about which modules have been installed and which not and then install them. the problem is that importing setup.py in main.py doesn't seem to import these packages in the global namespace of main.py so how can I make these two python files work as intended.

Your main.py file should import the setup.py file like this:

import setup
__import__('setup', globals={"__name__": __name__})

I would consider renaming your setup.py file to something like install_packages.py as 'setup' may conflict with previously assigned values - example:

import install_packages
__import__('install_packages', globals={"__name__": __name__})

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