简体   繁体   English

如何在单独的 setup.py 文件中进行所有导入,然后在 main.py 中导入此文件?

[英]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.我正在尝试制作一个安装脚本,它将在没有它的机器上安装所需的 python 模块。 so going with the recommended way of installing packages this is my setup.py所以使用推荐的安装包方式,这是我的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 :main.py为:

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.问题是,进口setup.py in main.py似乎没有导入这些包中的全局命名空间main.py我那么如何才能使这两个Python文件工作打算。

Your main.py file should import the setup.py file like this:您的main.py文件应该像这样导入setup.py文件:

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:我会考虑将您的setup.py文件重命名为install_packages.py东西,因为“setup”可能与之前分配的值冲突 - 例如:

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

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

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