首页 > 解决方案 > 通过执行更改的 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”。

标签: pythonlist

解决方案


通常,这不是您应该做的事情,因为它可能会导致不确定的行为,并且在出现错误时,可能会完全覆盖您的脚本并丢失数据。

如果您想更改脚本运行的日期,您应该以某种方式永久存储它。这可能在某个地方的单独文件中或在环境变量中。

但是要执行您的要求,您需要打开脚本,复制内容并根据需要修改内容,如下所示:

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)

推荐阅读