[英]Python script to input the next number in a sequence every time it runs.
I am trying to write a script that will have a count that starts a 001, and increasing by one every time that the script is run. 我正在尝试编写一个脚本,该脚本将具有一个启动001的计数,并且每次运行该脚本时都会增加一个。
I just help some help started this off, what can I do to set it up so that it knows where it start from every time? 我只是帮助一些帮助开始这个,我该怎么做才能设置它以便它知道每次从哪里开始? Is there is way that I can build it into the script to do this? 有没有办法可以将它构建到脚本中来执行此操作?
My bad ideas about how to do this so far: - Have the number(001) exported to a text file, and have the script change that number at the end of every script (001 +1). 到目前为止我对如何执行此操作的不好的想法: - 将数字(001)导出到文本文件,并让脚本在每个脚本(001 +1)的末尾更改该数字。
I feel like there has to be an easier way, and I'd prefer a way that was self-contained within the script. 我觉得必须有一个更简单的方法,我更喜欢在脚本中自包含的方式。 Can someone help point me in the right direction? 有人能指点我正确的方向吗?
Thanks for your input. 感谢您的输入。
if you want some kind of state persistance then your options are limited: 如果你想要某种状态持久性,那么你的选择是有限的:
Here's a quick example of saving state using INI files and JSON files. 这是使用INI文件和JSON文件保存状态的快速示例。 Both attempt to read a config file, update or initialize a counter, save the new counter back to the config, and then return the counter. 两者都试图读取配置文件,更新或初始化计数器,将新计数器保存回配置,然后返回计数器。
#!/usr/bin/env python3
import configparser
import json
from contextlib import suppress
def get_updated_ini_counter():
filename = 'config.ini'
section = 'general'
option = 'counter'
starting_count = 100
config = configparser.ConfigParser()
config.read(filename)
counter = 1 + int(config.get(section, option, fallback=starting_count - 1))
if section not in config:
config.add_section(section)
config.set(section, option, str(counter))
with open('config.ini', 'w') as f:
config.write(f)
return counter
def get_updated_json_counter():
filename = 'config.json'
option = 'counter'
starting_count = 100
config = {}
with suppress(FileNotFoundError):
with open(filename) as f:
config = json.load(f)
config[option] = 1 + config.get(option, starting_count - 1)
with open(filename, 'w') as f:
json.dump(config, f, indent=4)
return config[option]
if __name__ == '__main__':
print('ini counter = {}'.format(get_updated_ini_counter()))
print('json counter = {}'.format(get_updated_json_counter()))
This seems like a broad question. 这似乎是一个广泛的问题。 But say your script is hello.py
and it just printing "hello world"
, then for a simple case where you're running this script on your own desktop/laptop just include a few lines to keep track of when you last ran the script. 但是说你的脚本是hello.py
并且它只是打印"hello world"
,那么对于一个简单的情况,你在自己的桌面/笔记本电脑上运行这个脚本只需要包含几行来跟踪你上次运行脚本的时间。
import datetime
def hello():
print "hello, world"
if __name__ == "__main__":
now = datetime.datetime.now()
## create log
with open("logs.txt", "a") as log:
log.write(str(now) + "\n") ## write out to log
## run hello
hello()
Out: 日期:
>python hello.py
hello, world
>python hello.py
hello, world
>python hello.py
hello, world
>python hello.py
hello, world
>python hello.py
hello, world
>cat logs.txt
2017-04-21 10:38:46.629779
2017-04-21 10:38:47.229658
2017-04-21 10:38:47.664318
2017-04-21 10:38:47.957451
2017-04-21 10:38:48.279116
If you need to know the number of times you ran the script on a certain day/hour, you can just export this to Excel or something to show you the distribution of usage over time. 如果您需要知道在某一天/小时运行脚本的次数,您可以将其导出到Excel或其他内容以显示一段时间内的使用情况。
Here is the above example using atexit 以下是使用atexit的上述示例
The atexit module defines a single function to register cleanup functions. atexit模块定义了一个用于注册清理功能的函数。 Functions thus registered are automatically executed upon normal interpreter termination. 这样注册的功能在正常的解释器终止时自动执行。
import atexit
import datetime
def hello():
print "hello, world"
def saveDateTime():
now = datetime.datetime.now()
## create log
with open("logs.txt", "a") as log:
log.write(str(now) + "\n")
def goodbye():
try:
_dates = open("logs.txt").read()
_count = len(_dates)
except IOError:
_count = 0
print 'Goodbye, this script has been run %d times.' % (_count)
if __name__ == "__main__":
hello() ## run hello
atexit.register(saveDateTime) ## then log when you used this
atexit.register(goodbye) ## then log when you used this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.