Python:在子程序中使用模板和替换

发布于 2025-01-03 13:36:17 字数 496 浏览 3 评论 0原文

我有一个包含 $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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽袖吟 2025-01-10 13:36:17

使用 locals() 而不是 globals(),以便替换 DATETIME 的本地值:

  f.writelines(template.safe_substitute( locals() ))

PS。

''.join(f.readlines())

功能上相当于

f.read()

但速度较慢,因为它将文件分成几行,然后重新加入它们。您不妨使用f.read()

Use locals() instead of globals() so the local values for DATE and TIME are substituted:

  f.writelines(template.safe_substitute( locals() ))

PS.

''.join(f.readlines())

is functionally equivalent to

f.read()

but slower since it splits the file into lines, then rejoins them. You might as well use f.read().

逐鹿 2025-01-10 13:36:17

为什么不创建一个自己的字典,如下所示:

subs = {'DATE' = '20120209',
        'TIME' = '1200'}

f.writelines(template.safe_substitute(subs))

globals()locals() 包含的内容不只是 DATE时间。

Why don't you create a dictionary of your own like this:

subs = {'DATE' = '20120209',
        'TIME' = '1200'}

f.writelines(template.safe_substitute(subs))

globals() and locals() contain more than DATE and TIME.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文