如何在一行代码中插入变量?

时间:2016-05-01 05:24:09

标签: python

我想让用户使用字符串变量选择要打开的文件。基本上我想学习如何告诉Python在代码部分使用变量。

我有以下代码:

 Savebtn.setOnClickListener(new View.OnClickListener() {
         @Override
       public void onClick(View arg0) {
           if (DescriptionET.getText().toString().equals("") || 
               CalorieET.getText().toString().equals("0") ||
               CalorieET.getText().toString().equals("")){

                Toast.makeText(getActivity(), "Please enter information", 
                Toast.LENGTH_LONG).show();
            }
           else {
               saveDataToDB();
           }


         }
     });

在同一个文件夹中我有helloWorld.py:

def call_file(fn1):
    import fn1

filename = input("Name of the file to import")
call_file(filename)

2 个答案:

答案 0 :(得分:4)

正如您所发现的那样,import语句无法满足您的需求。试试这个:

from importlib import import_module

def call_file(fn1):
    return import_module(fn1)

filename = input("Name of the file to import: ")
usermodule = call_file(filename)

import_module函数允许您导入作为参数给出的模块。 python docs有关于此功能的更多信息。

实施例

ipython下运行,我们可以使用上面的代码导入os模块并以名称usermodule访问它:

In [3]: run t.py
Name of the file to import: os
In [4]: usermodule.stat('t.py')
Out[4]: os.stat_result(st_mode=33200, st_ino=97969455, st_dev=2066, st_nlink=1, st_uid=5501, st_gid=5501, st_size=196, st_atime=1462081283, st_mtime=1462081283, st_ctime=1462081283)

改进

如果无法导入用户要求的文件,代码应该处理错误,可能是这样的:

try:
    usermodule = call_file(filename)
except ImportError:
    print('Sorry, that file could not be imported.')

替代

也可以使用__import__

从变量名称导入模块
>>> mod = 'math'
>>> new = __import__(mod)
>>> new.cos(0)
1.0

但请注意,python documentation对此表示不满:

  

也不鼓励直接使用__import__()   importlib.import_module()

答案 1 :(得分:1)

您还可以使用sys模块实现与将模块导入为其他名称相同的效果。

import sys

def my_import(name):
    __import__(name)
    return sys.modules[name]

module = my_import('random') #just for testing
print module.randint(0,1) #just for testing

下面的代码可以用来抓住某个深度的模块!

def my_import(name):
    m = __import__(name)
    for n in name.split(".")[1:]:
        m = getattr(m, n)
    return m

m = __import__("xml.etree.ElementTree") # returns xml
m = my_import("xml.etree.ElementTree") # returns ElementTree
相关问题