python - 通过执行更改的 Python 脚本
问题描述
如何编写一个通过执行更改的脚本?例如,两行中存在两个 a have 脚本:
list = [1, 2, 3, 4, 5]
sliced_list = list[0:1]
执行它,第二行应该是:
sliced_list = list[1:2]
接着,
sliced_list = list[2:3]
每次运行此文件时,我都想修改变量“sliced_list”。
解决方案
通常,这不是您应该做的事情,因为它可能会导致不确定的行为,并且在出现错误时,可能会完全覆盖您的脚本并丢失数据。
如果您想更改脚本运行的日期,您应该以某种方式永久存储它。这可能在某个地方的单独文件中或在环境变量中。
但是要执行您的要求,您需要打开脚本,复制内容并根据需要修改内容,如下所示:
with open("/path/to/script.py", 'r+') as script:
contents = script.read()
# ... some string logic here
# Point cursor to the beginning of the file
# If the original contents were longing than the new contents
# you'll have unwanted data at the end of the file.
script.seek(0)
script.write(contents)
推荐阅读
- firebase - 如何在 us-central1 以外的区域使用 httpsCallable for web
- javascript - 向帖子添加新评论时“超出最大调用堆栈大小”
- r - 未使用 scale_fill_discrete 值
- php - 我从同一网络中的不同计算机获取相同的 IP 地址
- html - 为什么这个 html 'aside' 没有出现在侧面?
- node.js - 数据在数据库中发生变异但未更新
- r - 在 R 中更改系统发育中的尖端标签
- javascript - 如何停止打印“[object Object]”而不是对象本身?
- php - 使用imagick将AI文件转换为PNG
- extjs - 如何为 ext.js 网格中新添加的记录应用过滤器?