在python中动态执行包含python脚本的字符串,python脚本,python的exec方
在python中动态执行包含python脚本的字符串,python脚本,python的exec方
python的exec方法可以用来执行python脚本字符串,如下执行方法:
import sysimport StringIO# create file-like string to capture outputcodeOut = StringIO.StringIO()codeErr = StringIO.StringIO()code = """def f(x): x = x + 1 return xprint 'This is my output.'"""# capture output and errorssys.stdout = codeOutsys.stderr = codeErrexec code# restore stdout and stderrsys.stdout = sys.__stdout__sys.stderr = sys.__stderr__print f(4)s = codeErr.getvalue()print "error:\n%s\n" % ss = codeOut.getvalue()print "output:\n%s" % scodeOut.close()codeErr.close()
另外python中也有类似javascript的eval函数,可以用来计算字符串包含表达式的值。
相关内容
- wxPython 如何使用windows系统剪贴板,wxpython剪贴板,[Pyth
- python模拟登陆163获取邮件列表,python邮件列表,通过登陆
- Django CheatSheet,djangocheatsheet,from django.
- python socket.shutdown用法解释,,# -*- coding
- python遍历文件,python遍历,下面的python代码片
- jython编译java代码并执行,jython编译java,下面的代码片段
- python的lambda表达式实现递归,pythonlambda递归,[Python]代码
- Python sql注入检测工具代码,pythonsql注入代码,Python sql注
- python解决数独问题,python解决数问题,[Python]代码#
- wxpython下输出错误到控制台console,wxpythonconsole,import s
评论关闭