2015-12-24 18 views
2

靜態,我的意思是,對象(變量)不會改變。假設我有一個名爲my_static_vars的python模塊,它包含a,其起始值爲10(整數)。複製靜態變量(文件範圍)行爲

我有一個模塊中的一個功能:

def prntandinc(): #print and increase 
    print a 
    a += 1 

當我從另一個程序中導入模塊我希望它輸出11。但我不會問這是否沒有任何特別的限制。

我無法將它保存在一個文件中,不僅訪問會慢很多,我需要靜態的數據的大小非常大,每次都必須加載它。

我想我的模塊運行在一個永久循環中(好吧,直到它被告知不然),並聽取進程間通信(意味着我不會導入它,只是讓它接收來自「導入」程序的請求併發送必要的迴應)。現在,在我的情況下,這可能就足夠了 - 因爲該模塊所做的所有事情都會生成一個隨機序列號,並確保它不出現在used_serials(它應該是靜態的,因爲這是可能的)列表(我做的原因不想使用文件是因爲我在很短的時間內生成了大量的序列號) - 但我想知道是否有一個不那麼複雜的解決方案。

是否有任何不太複雜的實現方式?

回答

2

聲音就像數據庫一樣。只需import sqlite3

創建表(將它在當前目錄下保存爲serials.db):

import sqlite3 
conn = sqlite3.connect('serials.db') #Will create a new table as it doesn't exist right now 
cur = conn.cursor() #We will use this to execute commands 
cur.execute('''CREATE TABLE serials_tb (serial text)''') #for more than one column add a comma, as in a tuple, and write '[COL_NAME] [COL_TYPE]' without the apostrophes. You might want (as I suppose you only want a serial to be used once) to define it as a primary key 
conn.commit() 
conn.close() 

增加串行:

import sqlite3 
conn = sqlite3.connect('serials.db') #Will connect to the existing database 
cur = conn.cursor() 
data = ('MY_SERIAL',) #a tuple 
cur.execute('''INSERT INTO serials_tb VALUES (?)''', data) 
conn.commit() 
conn.close() 

選擇串行(看它是否已經存在):

import sqlite3 
conn = sqlite3.connect('serials.db') #Will connect to the existing database 
cur = conn.cursor() 
data = ('MY_SERIAL',) 
qry = cur.execute('''SELECT * FROM serials_tb WHERE serial=?''', data) 
#You can iterate over it and get a tuple of each row ('for row in qry:') 
#But to check if a col exists, in your case, you can do so: 
if len(qry.fetchall()) != 0: 
    #The serial is used 
else: 
    #The serial isn't used 

注意:顯然,您無需每隔一段時間輸入sqlite3時間(僅在每個文件中,但不是每次執行命令時,也不需要每次執行命令都要連接或關閉連接。在需要時提交更改,在開始時連接並在結束時關閉連接。 欲瞭解更多信息,你可以閱讀here

+0

我不敢相信我自己沒有想到它。非常感謝你,正是我需要的 –