Python - 时间戳变化的字符串

Python - String with timestamp changing

我正在尝试使用 datetime 包在 Python 中初始化一个字符串变量。我希望该字符串在初始化后保持不变,但由于某些奇怪的原因(至少对我来说很奇怪),它正在发生变化。

基本上,当我尝试时:

timestamp = datetime.datetime.now().strftime('%m-%d-%Y.%I_%M_%S_%p')
base_directory = "C:\Users\Ben\report_" + timestamp + "\"
print base_directory #prints C:\Users\Ben\report_02-13-2015_02_02_24_PM
time.sleep(5)
logs_directory = base_directory + "logs\"

当我回去使用 logs_directory 变量时,我希望它是

C:\Users\Ben\report_02-13-2015_02_02_24_PM\logs\

然而,反而是:

C:\Users\Ben\report_02-13-2015_02_02_29_PM\logs\ #!!!

就好像当我访问日志目录变量时,它会返回并再次重新计算 base_directory 变量,而不是检索已设置为 base_directory 的值。这是 Python 中的预期功能吗?我不是,因为我似乎无法从 IDLE shell 触发此问题 - 它仅在我 运行 我的 Python 来自 pydev 的程序时发生。但是,如果这是预期的功能,我该如何重写我的代码以获得我期望的结果?谢谢!

我不确定它是否相关,但我正在 nose 单元测试中访问这个变量。这是在 Python 2.7.


更新:这里有一些独立的代码可以更好地说明正在发生的事情。它实际上看起来确实在某种程度上与鼻子有关:

import nose, os, sys, time

timestamp = time.strftime('%m-%d-%Y.%I_%M_%S_%p')
base_directory = "C:\Users\Ben\Desktop\report_" + timestamp + "\"
logs_directory = base_directory + "logs\"

def test_me():
    print base_directory
    print logs_directory

if __name__ == '__main__':
    os.makedirs(base_directory)
    os.makedirs(logs_directory)
    print base_directory
    print logs_directory

    time.sleep(5)

    #Without the nocapture argument, nose will internally log all
    #stdout output, and will not output anything to the console.
    argv = (sys.argv[:])
    argv.insert(1, "--nocapture")
    nose.main(argv=argv)  #This will run test_me()

这是输出:

C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\
C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\logs\
C:\Users\Ben\Desktop\report_02-13-2015.04_27_37_PM\
C:\Users\Ben\Desktop\report_02-13-2015.04_27_37_PM\logs\

我期待:

C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\
C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\logs\
C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\
C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\logs\

这是怎么回事?为什么 nose 会重新评估已经初始化的字符串?我如何重写我的代码以使其达到我的预期?谢谢!

我可以重现问题:

#!/usr/bin/env python
import time

timestamp = time.strftime('%S')

def test_me():
    print('test_me ' + timestamp)
    assert 0

if __name__ == '__main__':
    import nose # $ pip install nose
    print('main ' + timestamp)
    time.sleep(3)
    nose.main()

print('main ' + timestamp)print('test_me ' + timestamp) 显示不同的结果。

nose 在睡眠后在内部导入模块,因此 timestamp 不同:实际上有两个对象 __main__.timestampmodule_name.timestamp.

如果模块既 运行 作为脚本又可以导入,则不应具有变量全局状态。参见 Executing the main module twice

这是一个没有 nose 的例子:

#!/usr/bin/env python
"""Execute main module twice."""
import time

timestamp = time.strftime('%S')

def print_timestamp(prefix):
    print(prefix + timestamp)

if __name__ == '__main__':
    print_timestamp('main')
    time.sleep(3)
    import test_exec_main_twice
    test_exec_main_twice.print_timestamp('module')

将其保存到 test_exec_main_twice.py 文件并 运行。