免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2906 | 回复: 8
打印 上一主题 下一主题

【解决】[变量应用问题]testfun是一个函数.. [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-12-03 14:13 |只看该作者 |倒序浏览
大家好,初学Python,有两个问题请教大家:
问题一:
  1. def ImportDef(pkgdir,pkgname):
  2.     try:
  3.         from pkgdir.pkgname import pkgname
  4.         return True
  5.     except Exception,e:
  6.         print "Error Info: %s" % e
  7.         return False

  8. ImportDef('testdir','test')
复制代码
我现在在testdir目录下面有一个文件test.py
现在我想根据参数的需要来导入相关文件,所以定义了pkg_dir和pkg_name变量。但是我代码这样写,导入是不成功的。
如果我直接写成:
  1. from testdir.test import test
复制代码
则是可以的。请问该问题如何解决?
问题二:
  1. def testfun(str):
  2.     print "testfun: ",str

  3. def testfun1(str):
  4.     print "testfun1: ",str

  5. str1="testfun"
  6. str1()
复制代码
我想实现的效果是:我的str1是一个变量,直接执行变量定义的函数。
请问大家,上面两个问题如何解决?
非常感谢!

[ 本帖最后由 wzhuzhu 于 2009-12-3 22:09 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2009-12-03 15:03 |只看该作者
第一个:把脚本名字改了,别叫test.py
第二个:可以简单的用locals()[str1]() 这样来调用,当然locals可以换成vars,globals

论坛徽章:
1
天蝎座
日期:2013-10-23 21:11:03
3 [报告]
发表于 2009-12-03 16:43 |只看该作者

回复 #1 wzhuzhu 的帖子

对于第二个问题

  1. def testfun(str):
  2.     print "testfun: ",str

  3. def testfun1(str):
  4.     print "testfun1: ",str

  5. str1 = "testfun"
  6. eval(str1).__call__('success')
  7. str1 = "testfun1"
  8. eval(str1)('success')
复制代码

>>> help(eval)
Help on built-in function eval in module __builtin__:

eval(...)
    eval(source[, globals[, locals]]) -> value
   
    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

这里利用了eval返回值是表达式,而函数调用也是表达式

论坛徽章:
1
天蝎座
日期:2013-10-23 21:11:03
4 [报告]
发表于 2009-12-03 16:58 |只看该作者

回复 #1 wzhuzhu 的帖子

对于第一个问题
  from 'testdir'.'test' import 'test'
的形式铁定行不通
暂时又想不出什么办法转换成testdir和test
因为这两个变量不存在,不能访问

暂时想到一种方法,扩展性要差一些
就是利用getopt,类似命令常用的不同选项的方式
不同的选项导入不同模块

等待更好的方法……

论坛徽章:
0
5 [报告]
发表于 2009-12-03 18:44 |只看该作者
hasattr('testdir','test')

论坛徽章:
0
6 [报告]
发表于 2009-12-03 22:07 |只看该作者

[问题解决]

对于第二个问题的解决,请参考楼上几位弟兄的发言。
对于第一个问题,我多次试探。反复查看核心编程的第14章,得到解决:

  1. def ImportDef(pkgdir,pkgname):
  2.     try:
  3.         #from pkgdir.pkgname import pkgname
  4.         imp_cmd = "from "+pkgdir+"."+pkgname+" import "+pkgname
  5.         exec(imp_cmd)
  6.         return True
  7.     except Exception,e:
  8.         print "Error Info: %s" % e
  9.         return False

  10. ImportDef('testdir','test')
复制代码

通过使用exec就可以达到,根据传入的变量来导入相应的文件。
非常感谢大家的关注。

论坛徽章:
0
7 [报告]
发表于 2009-12-04 10:56 |只看该作者
没必要用exec的,有现成的__import__可以用...

论坛徽章:
1
天蝎座
日期:2013-10-23 21:11:03
8 [报告]
发表于 2009-12-04 11:42 |只看该作者

回复 #7 3227049 的帖子

学习一下
__import__(...)
    __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
   
    Import a module.  The globals are only used to determine the context;
    they are not modified.  The locals are currently unused.  The fromlist
    should be a list of names to emulate ``from name import ...'', or an
    empty list to emulate ``import name''.
    When importing a module from a package, note that __import__('A.B', ...)
    returns package A when fromlist is empty, but its submodule B when
    fromlist is not empty.  Level is used to determine whether to perform
    absolute or relative imports.  -1 is the original strategy of attempting
    both absolute and relative imports, 0 is absolute, a positive number
    is the number of parent directories to search relative to the current module



试了一下

  1. def ImportDef(pkgdir,pkgname):
  2.     try:
  3.         module_name = pkgdir + '.' + pkgname
  4.         from_list = [pkgname]
  5.         global m
  6.         m = __import__(name=module_name, fromlist=from_list)
  7.         return True
  8.     except Exception,e:
  9.         print "Error Info: %s" % e
  10.         return False

  11. m = 0
  12. ImportDef('os','path')
  13. help(m)
  14. dir(m)                               # no output???
复制代码

奇怪的是为什么最后的dir没有输出呢
在命令行下help和dir都有输出,为什么写入脚本后执行只有help有输出,dir就没有?

论坛徽章:
1
天蝎座
日期:2013-10-23 21:11:03
9 [报告]
发表于 2009-12-04 13:32 |只看该作者

回复 #8 openspace 的帖子

刚看了一下
dir返回的是字符串的列表
       print dir(m)
就可以了
关于help没有描述返回值的类型,猜想内部使用了print输出
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP