Python:在子程序中使用模板和替换
我有一个包含 $DATE 和 $TIME 的模板文件,将替换为当前值。 只要我在主程序中有 evruthing,这就可以正常工作。 不过,我想将替换位放入子例程中,例如:
def substitute():
DATE = '20120209'
TIME = '1200'
f = open( 'template.txt' )
template = string.Template( ''.join(f.readlines()) )
f.close()
# substitute and save
f = open( 'current.txt', 'w+' )
f.writelines(template.safe_substitute( globals() ))
f.close()
正如我所说,如果我将其放在主程序中,则效果很好。但在 def 版本中,仅当 DATE 和 TIME 已在主程序中定义时才有效。我不想这样做。
有什么想法可能是什么问题吗?
I have a template file cotaining $DATE and $TIME to be substituted by the current values.
This works fine as long as I have evruthing in the main program.
However I want to put the substitution bit into a subroutine e.g. lie this:
def substitute():
DATE = '20120209'
TIME = '1200'
f = open( 'template.txt' )
template = string.Template( ''.join(f.readlines()) )
f.close()
# substitute and save
f = open( 'current.txt', 'w+' )
f.writelines(template.safe_substitute( globals() ))
f.close()
As I said, this works fine if I have it in the main program. But in the def version it only works if DATE and TIME are already defined in the main program. Which I do dont want to do.
Any ideas what the problem could be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
locals()
而不是globals()
,以便替换DATE
和TIME
的本地值:PS。
功能上相当于
但速度较慢,因为它将文件分成几行,然后重新加入它们。您不妨使用
f.read()
。Use
locals()
instead ofglobals()
so the local values forDATE
andTIME
are substituted:PS.
is functionally equivalent to
but slower since it splits the file into lines, then rejoins them. You might as well use
f.read()
.为什么不创建一个自己的字典,如下所示:
globals()
和locals()
包含的内容不只是DATE
和时间。
Why don't you create a dictionary of your own like this:
globals()
andlocals()
contain more thanDATE
andTIME
.