简体   繁体   English

Python 通过执行改变的脚本

[英]Python Script that is changes by execution

how can I write a script that it changes by execution?如何编写一个通过执行更改的脚本? For example, two a have script exist from two row:例如,两行中存在两个 a have 脚本:

list = [1, 2, 3, 4, 5]
sliced_list = list[0:1]

Executing it, 2nd row should be:执行它,第二行应该是:

sliced_list = list[1:2]

and then,接着,

sliced_list = list[2:3]

I want to modify variable "sliced_list" everytime I run this file.每次运行此文件时,我都想修改变量“sliced_list”。

Generally this is not something you should ever want to do, since it is likely to result in non-deterministic behavior, and in the event of a bug its possible to completely overwrite your script and lose data.通常,这不是您应该做的事情,因为它可能会导致不确定的行为,并且在出现错误时,可能会完全覆盖您的脚本并丢失数据。

If you want to change the date your script is operating on you should store it persistently in some fashion.如果您想更改脚本运行的日期,您应该以某种方式永久存储它。 This could be in a separate file somewhere or in an environment variable.这可能在某个地方的单独文件中或在环境变量中。

But to do what your asking you would need to open the script, copy the contents, and modify the content as you desire like this:但是要执行您的要求,您需要打开脚本,复制内容并根据需要修改内容,如下所示:

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)

You could save the start index into a file when you run the script.您可以在运行脚本时将开始索引保存到文件中。 Then increment it and save it.然后增加它并保存它。 Something like what is shown below.如下所示。

import os
List=[1,2,3,4,5]
file=open('file.txt','r+')
start_index=int(file.read())
print(List[start_index:start_index+1])
file.close()
os.remove('file.txt')
file=open('file.txt','w')
file.write(str(start_index+1))
file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM