python - 有没有办法检测脚本本身中的代码块是否包含特定单词
问题描述
...并根据该单词的存在来决定该块的执行?
例如我有这个:
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
的人,答案是大量的计算
解决方案
你可以这样做:
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脚本改变自己?
推荐阅读
- python - Scrapy无法转到下一页
- codeigniter - codeigniter - 验证激活码后重定向用户
- python - python - 如何在没有身份验证的情况下使用python从telnet获取数据
- angular - 带有 asObservable 的 Subject.error 导致 Angular 6 异步管道快速消耗所有系统内存
- android - 回收站视图未显示内容
- css - Gmail 中的基础电子邮件错误
- bash - 任何工具可以并行化具有不同 CPU 要求的 bash 命令?
- python - 如何在python数据框中将对象数据类型转换为浮点数
- javascript - 通过 API 中的 req.query 将元数据信息附加到 Gridfs 文档文件 - Node.js Expresss.js MongoDB Multer Gridfs 流
- symfony - Symfony3.4 / Doctrine:FROM 子句中的子查询:错误:未定义“SELECT”类