简体   繁体   中英

how to pass value of a variable to import statement in python

I'm really new to python. I'm using 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. 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.

You can use __import__() function instead to import modules. 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.

You should use importlib module

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+

If you do not want to import the importlib module, this does it:

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 .

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