我有一段Python(2.7)代码,它连接到mySQL DB并从csv文件(DBCommit())输入内容。如果MySQL提交(DBCommit)成功完成,我想清除CSV(ClearCache())文件 ONLY 。如果不是(即连接有问题,或接受数据等),则保留CSV以便稍后处理。我是否使用,尝试,子处理,线程或多线程?
BTW我是编码的新手!任何指针都会很棒!
Code:
*************************************
import subprocess, MySQLdb, os, sys, select, shutil
#***********************************
#Define Functions
#***********************************
#Cache file location - used as a transaction for the DB
CachePath = '/home/pi/GistCache.csv'
#Used as the initial log file. Another process writes to this file.
LogPath = '/home/pi/GistLog.csv'
#Connects to the DB and commits the CachePAth file to the MySQL DB
def DBCommit():
cnx = MySQLdb.connect(user='user',passwd='password',host='ip',db='dbname')
cur = cnx.cursor()
DataImport = ("""LOAD DATA INFILE "/home/pi/GistCache.csv" INTO TABLE PI_GIST_LOG.PI_Gist_Log_Tbl COLUMNS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES (RFID,TimeStamp,MACAddr,IPAddr)""")
cur.execute(DataImport)
cnx.commit()
cnx.close()
#opens the LogPath and Cache Path files, copys the content from LogPath to CachePath
def Append():
with open(LogPath, "r") as logopen:
next(logopen)
for line in logopen:
with open(CachePath, "a") as cacheopen:
cacheopen.write(line)
#Creates a new LogPath File
def NewLogPath():
with open(LogPath, 'w') as Log:
Log.write("ID,RFID,TimeStamp,MAC,IP,\n")
#Deletes the LogPath and Creates a new version
def ClearLogPath():
os.remove(LogPath)
NewLogPath()
#deletes CachePath
def ClearCache():
os.remove(CachePath)
#Reboots the PI
def Restart():
command = "/usr/bin/sudo /sbin/shutdown -r now"
import subprocess
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
print output
#*********************************
#Start Process
#*********************************
#checks if the CachePath file already exists - means the previous code failed to complete. If it does, then check LogPath. If that exists, then append the LogPath to CachePath, Clear log and upload to DB.
#If logPath doesn't exist, create it and reboot.
if os.path.lexists(CachePath):
if os.path.lexists(LogPath):
Append()
ClearLogPath()
*********************
#This is what I want to run first DBConnect.
DBCommit()
#Only if DBconnect is successful, should it run ClearCache
ClearCache()
*********************
else:
NewLogPath()
Restart()
#If Cache doesn't exist, Check if LogPath exists. If it does, rename logpath to cachepath and recreate logpath. Commit to DB. Otherwise is LogPath doesn't exist, create it and reboot the PI
else:
if os.path.lexists(LogPath):
shutil.move(LogPath, CachePath)
NewLogPath()
DBCommit()
ClearCache()
#If Cache and Log don't exist, recreate log and reboot
else:
NewLogPath()
Restart()
答案 0 :(得分:0)
你可以使用
if DBCommit():
## do stuff
如果DBCommit返回任何内容(0,False等除外),它将被视为True,并执行操作。
否定:如果不是DBCommit()
您的代码:
def DBCommit():
cnx = MySQLdb.connect(user='user',passwd='password',host='ip',db='dbname')
cur = cnx.cursor()
DataImport = ("""LOAD DATA INFILE "/home/pi/GistCache.csv" INTO TABLE PI_GIST_LOG.PI_Gist_Log_Tbl COLUMNS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES (RFID,TimeStamp,MACAddr,IPAddr)""")
cur.execute(DataImport)
cnx.commit()
cnx.close()
return True
....
if os.path.lexists(CachePath):
if os.path.lexists(LogPath):
Append()
ClearLogPath()
*********************
#This is what I want to run first DBConnect.
DBCommit()
#Only if DBconnect is successful, should it run ClearCache
if DBCommit():
ClearCache()
*********************
else:
NewLogPath()
Restart()
答案 1 :(得分:0)
如果DBCommit()
函数中的任何内容失败,您当前的代码会发生什么?我不会自己尝试,但可能会引发一些异常,将在此时中断程序执行,从而阻止调用ClearCache()
。如果您发现(在测试了所有错误条件后,您可以想到)DBCommit
中的某些可能错误不会引发异常,那么您只需要在DBCommit
中处理这些情况并确保它们是DO提出异常。