简体   繁体   English

Python脚本,每次运行时都会在序列中输入下一个数字。

[英]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)的末尾更改该数字。

  • This number will also be in a spreadsheet, so have the script read to value from the spreadsheet, and add one to that value. 此数字也将位于电子表格中,因此脚本会从电子表格中读取值,并将该值添加到该值。

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: 如果你想要某种状态持久性,那么你的选择是有限的:

  1. save the state into a file as you suggest in your question (either a text file or spreadsheet, but spreadsheet is harder to do) 将状态保存到您在问题中建议的文件中(文本文件或电子表格,但电子表格更难)
  2. change your concept so that instead of "running the script" multiple times, the script is always running, but you give it some kind of signal (keyboard input, GUI with a button etc) to let it know to increment the counter 更改你的概念,以便不是多次“运行脚本”,脚本总是在运行,但你给它一些信号(键盘输入,带按钮的GUI等)让它知道增加计数器
  3. split your script into two halves, a server script and a client. 将脚本分成两半,一个服务器脚本和一个客户端。 the server would listen for connections from the client, and keep track of the current count, the client would then connect and tell the server to increment the count, if needed it could also send the previous or new count back to the client for some kind of output. 服务器将侦听来自客户端的连接,并跟踪当前计数,然后客户端将连接并告诉服务器增加计数,如果需要,它还可以将先前或新计数发送回客户端以用于某种类型输出 this would prevent having many writes to disk, but the count would be lost if the server process is closed. 这样可以防止对磁盘进行多次写入,但如果服务器进程关闭,则计数将丢失。

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或其他内容以显示一段时间内的使用情况。

Update, using atexit: 使用atexit更新:

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.

相关问题 从命令行运行 python 脚本时,PythonWin 也会运行。 我怎样才能避免这种情况? - When running a python script from command line, PythonWin also runs. How can I avoid this? 运行GET请求循环的Python脚本抛出“ KeyError”,但并非每次都抛出 - Python script that runs GET request loop throws “KeyError”, but not every time Python:每次函数运行时如何增加数字和存储变量 - Python: how to increment number and store in variable every time function runs 为什么我的Python脚本每次运行都会给我一个错误? - Why is my Python script giving me an error every time it runs? 每次运行python脚本时更改Excel Sheet - Changing Excel Sheet every time python script runs Python Pandas下一个序列号 - Python Pandas Next Sequence Number 每次脚本运行时更改函数名称 - Changing function name every time script runs 每次运行 Python 脚本时如何创建新的 excel 文件? - How can I create a new excel file every time a Python script runs? 每次运行 python 脚本时,如何使用新结果更新 google 表? - How to update google sheet with new outcome every time python script runs? 使用 Python 创建一个脚本,该脚本会按顺序为用户提供下一个素数并询问他们是否想要另一个 - Using Python to create a script that gives the user the next prime number in sequence and asks if they want another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM