【问题标题】:Need a variable to retain it's value when the script is executed again (Python)再次执行脚本时需要一个变量来保留它的值(Python)
【发布时间】:2017-01-31 09:12:27
【问题描述】:

目前我正在研究 tweepy,我需要将 tweet id 存储在一个变量中,并希望它在脚本再次运行时保留这个值。我知道我可以使用文件和数据库来做到这一点,但我想使用环境变量来做到这一点。寻找正确方向的推动力。我已经使用命令 >export en=1 从终端设置了环境变量 这是我正在使用的代码:

#!/usr/bin/env python
# encoding: utf-8

import tweepy 
import time
import random
import os
t=time.time()

#my api keys 
consumer_key = "xxx"
consumer_secret = "xxx"
access_key = "xxx"
access_secret = "xxx"


toReply="xxx"
rt=['hello','hi','okay','bye']
#rt=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','you','suck','bruh',':P']
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
ts=api.user_timeline(screen_name=toReply,count=1)
#g=open('id.txt','r')
#x=g.read()
#g.close()
x=os.environ["en"]
print x
l=[]
#print dir(ts)
#print ts.max_id
#print type(ts.max_id)
def unique(y,l):
    for i in range(0,len(l)):
        if l[i]==y:
            return 0
if int(x)!=ts.max_id:        
    for tweet in ts:
        for i in range(0,len(rt)+1):
            y=random.choice(rt)
            #print y
            if(unique(y,l)!=0):
                    #print("unique")
                    api.update_status("@" + toReply + " "+y, in_reply_to_status_id = tweet.id)
                    #print y
                    l.append(y)

    os.environ["en"]=str(ts.max_id)
    print os.environ["en"]
    '''
    f=open('id.txt','w')
    f.write(str(ts.max_id))
    f.close()
    ''' 
t1=time.time()-t
print t1

【问题讨论】:

标签: python environment-variables


【解决方案1】:

在评论中建议使用 Pickle,但它有一个很大的缺点,即您无法从 Python 程序之外编辑 pickle。

如果您想要 Windows .ini 文件之类的东西,那么您想要的 Python 库模块是 ConfigParser 根据这个答案How to read and write INI file with Python3?

另一种可能性是使用 JSON(模块 json)。这可能非常复杂,但如果您坚持使用单个键:值对字典,则不是。

还有一种可能是 YAML。

在所有情况下,您可能还希望atexit 注册退出处理程序,以便在程序合理退出时保存配置变量的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多