简体   繁体   English

如何在python中将变量的值传递给import语句

[英]how to pass value of a variable to import statement in python

I'm really new to python. 我是python的新手。 I'm using python<2.7. 我正在使用python <2.7。 I have to import a file whose name I don't know at start. 我必须在开始时导入一个名字我不知道的文件。 In fact I have to pass the name of file through command prompt, now I have read the name and stored in variable, but I don't know how to pass it to import statement. 实际上我必须通过命令提示符传递文件名,现在我已经读取了名称并存储在变量中,但我不知道如何将它传递给import语句。 I'm trying the code 我正在尝试代码

str = sys.argv[lastIndex]
from "%s" import *,str

but it's giving the error 但它给出了错误

File "IngestDataToMongo.py", line 86
from "%s" import *,str
        ^
SyntaxError: invalid syntax

So how to do it. 那怎么做呢。 Also is it possible with python <2.7, because for some reasons I can't change the version of Python or install anything where this code is running. 也可以使用python <2.7,因为由于某些原因我无法更改Python的版本或安装运行此代码的任何内容。

You can use __import__() function instead to import modules. 您可以使用__import__()函数来导入模块。 It accepts variables as its arguments. 它接受变量作为参数。

But first of all, make sure you really need that - 90% of the time people do not really need that function. 但首先,确保你真的需要它 - 有90%的时间人们并不真正需要这个功能。

You should use importlib module 您应该使用importlib模块

import importlib

mdl = 'urllib'
your_module = importlib.import_module(mdl)
your_module.quote
>>> <function urllib.quote>

EDIT 编辑

Thanks to Tadeck - This does work for python 2.7 and 3.1+ 感谢Tadeck - 这适用于python 2.7和3.1+

If you do not want to import the importlib module, this does it: 如果您不想导入importlib模块,则执行以下操作:

import sys
s = sys.argv[lastIndex]
def is_save(s):
    #test if s is a valid argument
    return True or False

if is_save(s):
    exec('from %s import *'%s)

Note: the is_save function is needed to avoid abuse of the script since the usage of exec (or eval ) is potentially dangerous . 注意:需要使用is_save函数来避免滥用脚本,因为exec (或eval )的使用具有潜在的危险性

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

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