【问题标题】:Writing a unique identifier to script?将唯一标识符写入脚本?
【发布时间】:2010-04-19 16:15:00
【问题描述】:

我想编写一个下标,每次运行时都会向脚本添加唯一标识符(机器时间)。但是,每次我编辑脚本(在 IDLE 中)时,标识符都会被覆盖。有没有一种优雅的方式来做到这一点。我编写的脚本如下所示。

import os, time

f = open('sys_time_append.py','r')
lines = f.readlines()
f.close()
fout = open('sys_time_append.py','w')


for thisline in lines:
    fout.write(thisline)
fout.write('\n#'+str(time.time())+' s r\n')
fout.close()

感谢您的帮助。

【问题讨论】:

    标签: python file rewrite


    【解决方案1】:

    我认为这是一件危险的事情,但它确实有效:

    import os, time
    
    print "Hi, ", __file__, '!'
    
    with open(__file__, 'a') as fout:
        fout.write('\n#'+str(time.time())+' s r\n')
    

    请注意,我也将脚本名称设为__file__(但这不是完整路径名,因此如果更改 cwd 可能会出现问题)。

    或者我在“在 IDLE 中编辑”的参考中遗漏了一些重要的东西?当脚本附加到脚本时,您可能无法在编辑窗口中激活脚本。程序不可能知道哪个有“控制权”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 2014-03-05
      • 2012-06-02
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多