之前,在程序编写过程中,有一个想法,那就是 传参,来跟据参数调用指定的方法。
当然,我们用 if 来判断是可以实现,但显然不是我想要的。
后来,也是通过其它方法实现的。
今天又想使用类似的方法。那就是在处理时间 datatime 时我又想试一下我的想法。
显然,我发现了,python 内置函数 exec()
这里,摘录一下,函数介绍
globals:可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象。
# 我们正常输出一个字符串
print('hello')
# 如果,我们是通过,input 标签来输入一个代码,想让他执行了,那就这样
str_code = input("print('hello')")
# str_code 的类型没有疑问,是 <class 'str'>
# 我们让他执行了,就像下面这样
exec(str_code )
这样的效果就是等于 执行了 print('hello')
以前在,某 php 程序中见过,好像java中也有。
# 比如我想动态提取时间的年月日,像下面这样
def dur(end,type,start='',str='%Y-%m-%d %H:%M:%S'):
if start == '':
start_time = datetime.now().strftime(str)
fstr = 'print( datetime.strptime(end, str).' + type +')'
exec(fstr)
return False
这样就输出了,可以是year , month ....
但是 不是在里面使用return , SyntaxError: 'return' outside function
等进一步测试,object code
当然,如果需要返回值的话,我们也可以使用,eval
完整示例:
def dur(end, type, start='', f_str='%Y-%m-%d %H:%M:%S'):
if start == '':
start_time = datetime.now().strftime(f_str)
fstr = '''datetime.strptime(end, f_str).{}'''.format(type)
e_str = '''a = datetime.strptime('{}', '{}').{}'''.format(str(end), f_str, type)
# exec(fstr) 无返回值 , 且不能直接使用外部的变量。 但可以使用globals() 来接受结果。
# execute 执行的意思
result={}
# exec(fstr, globals(), result) # 结果 NameError: name 'end' is not defined
# 发现第一个参数 是未定义的,就是使用不了传进来外部变量。
exec(e_str, globals(), result) # 这个就正常执行了。
print(result)
print(fstr)
return eval(fstr)
print('exec_和_eval', dur("2030-01-01 10:00:00",'year'))