首页 > 解决方案 > 有没有办法检测脚本本身中的代码块是否包含特定单词

问题描述

...并根据该单词的存在来决定该块的执行?

例如我有这个:

for frame in range(10):
    with open('frame_init.gro', 'w') as g:
        # do something
    with open('frame_next.gro', 'w') as h:
        # do something

当“帧”达到 9 时,我根本不希望整个with open('frame_next.gro', 'w') as h块执行。当然,我考虑过将它封装在 a 中,if frame != 9但我实际的整个代码真的很长,所以如果可能的话,如果我可以在脚本本身中扫描我的脚本,那就太好了。

对于那些对其他事情感到好奇frame_next.gro的人,答案是大量的计算

标签: python

解决方案


你可以这样做:

a = 0
b = 1
print a + b

with open(__file__, 'r') as f:
    lines = f.read().split('\n')
    val = int(lines[0].split(' = ')[-1])
    new_line = 'a = {}'.format(val+1)
    new_file = '\n'.join([new_line] + lines[1:])

with open(__file__, 'w') as f:
    f.write('\n'.join([new_line] + lines[1:]))

从这里: 我怎样才能让python脚本改变自己?


推荐阅读