简体   繁体   English

根据参数导入Python模块

[英]Import Python module based on argument

I'm trying to dynamically import a python-based SQL query module from a sub-folder, and that folder is obtained by using the argparse module. 我正在尝试从子文件夹动态导入基于python的SQL查询模块,并且该文件夹是通过使用argparse模块获得的。

My project structure : 我的项目结构:

main_file.py
Data_Projects/
   ITA_data/
      __init__.py
      sqlfile.py
   UK_data/
      __init__.py
      sqlfile.py

Within main_file.py is the argparse module with the argument 'dir' containing the location of the specified directory ie 在main_file.py中是argparse模块,其参数'dir'包含指定目录的位置,即

parser.add_argument('--dir', default='Data_Projects/ITA_data/', type=str,
                        help="set the data directory")

My understanding thus far is that modules should be imported at the top and to import just one sql query I would use: from Data_Project.ITA_data import sqlfile 到目前为止,我的理解是模块应该在顶部导入,并且只导入我将使用的一个SQL查询: from Data_Project.ITA_data import sqlfile

I know I can't set the import statement after the args have been defined, so how can I keep the format correct with the imports at the top, and yet retrospectively update this with the arguments that get defined afterwards? 我知道在定义了args之后我无法设置import语句,那么如何在顶部的导入中保持格式正确,又如何使用之后定义的参数追溯更新呢?

Many thanks. 非常感谢。

UPDATE UPDATE

Thanks to the below answer. 感谢以下答案。 I've now tried to assign : 我现在尝试分配:

sqlfile = __import__(in_arg.dir + 'sqlfile.py')

However I'm getting the following error: 但是我收到以下错误:

*** ModuleNotFoundError: No module named 'Data_Projects/ITA_data/sqlfile' *** ModuleNotFoundError:没有名为“ Data_Projects / ITA_data / sqlfile”的模块

I've tried using things like 我已经尝试使用类似的东西

os.path.join(Path(__file__).resolve().parents[0], in_arg.dir + 'sqlfile')

If it helps, when I try just : 如果有帮助,当我尝试时:

__import__('Data_Projects') - works fine
__import__('Data_Projects/ITA_data') - doesn't work - ModuleNotFound

And as a check to verify I'm not crazy: 并检查我没有疯:

os.path.exists('Data_Projects/ITA_Data/sqlfile.py') >>> True
os.path.exists(in_arg.dir + 'sqlfile.py') >>> True

You can use __import__(filename: str) function instead of import statement. 您可以使用__import__(filename: str)函数代替import语句。 It does the same: 它的作用相同:

# option 1
import foo as bar
# option 2
bar = __import__('foo')

If you need to import from aside, you need to add your directory to module search paths . 如果需要从一边导入,则需要将目录添加到module search paths There are several ways to achieve that, depending on your version of Python. 有多种方法可以实现此目标,具体取决于您的Python版本。 You can find them all in great post: 您可以在精彩的帖子中找到它们:

How to import a module given the full path? 给定完整路径,如何导入模块?

I don't see anything wrong with 我没有发现任何问题

import argparse
parser = ...
parser.add_argument('data', choices=['UK', 'ITA'])
args = parser.parse_args()
if args.dir == 'UK':
    import UK_data as data
elif args.dir == 'ITA':
    import ITA_data as data
else ...

You could refine this with functions and __name__ etc. But a conditional import is ok, just so long as it occurs before the data module is used. 您可以使用函数和__name__等进行优化。但是,只要在使用data模块之前进行条件导入,就可以了。

The issue was resolved by using : 该问题已通过使用解决:

import sys
sys.path.insert(0, os.getcwd() + "/" + in_arg.dir)

This sets the PYTHONPATH variable to include the directory I want (which changes depending on the argument) to use to search for the file. 这将PYTHONPATH变量设置为包括我要用于搜索文件的目录(该目录根据参数而变化)。

From there using grapes help it was a case of doing: 从那里开始使用葡萄帮助就是一个例子:

sqlfile = __import__('sqlfile')

And from there I could use the variable to perform the relevant sql query. 从那里我可以使用变量执行相关的sql查询。

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

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