尝试从if / else语句内部读取和写入全局变量,但出现错误
SyntaxError:在全局声明之前将名称“ PREV_HASH”分配给了
我尝试使用全局语法,但无法正常工作。不习惯python中的全局v局部变量
PREV_HASH = ''
LOGFILE_DIRECTORY = 'c:\\securelog\\securelog_logs\\'
ARCHIVE_FOLDER = 'c:\\securelog\\securelog_archive\\'
WORKFILES_FOLDER = 'c:\\securelog\\securelog_workfiles\\'
TMP_FOLDER = 'c:\\securelog\\processed\\'
COMPLETED_FOLDER = 'c:\\securelog\\completed\\'
CHAIN_FILE = WORKFILES_FOLDER + 'chain_info.txt'
#check if this is the first run, if it is hardcode the block & previous hash and pass the hash
if chain_list[0] == 1:
fileHandle = open (CHAIN_FILE, 'r+')
fileHandle.write('1,0,' + hasher.hexdigest())
fileHandle.close()
global PREV_HASH
PREV_HASH = hasher.hexdigest()
#print("1 previous hash is: " + str(PREV_HASH))
else:
#update list with hash of current and previous block
###del (chain_list[1:])
global PREV_HASH
chain_list.insert (1,PREV_HASH)
print("2 previous hash is: " + str(PREV_HASH))
chain_list.insert (2,hasher.hexdigest())
fileHandle = open (CHAIN_FILE, 'a')
print('2 what is the chain list at this point:' + str(chain_list))
#Write the contents of the list to the chain file on a new line and separate with a comma
fileHandle.write(',' + str(chain_list[2]))
fileHandle.close()
PREV_HASH = hasher.hexdigest()
我希望在脚本的第一次运行中创建一个新文件,并包含一个包含1、0的行以及在上一步中生成的哈希键(“ hasher.hexdigest()”) 然后,该哈希将保存在全局变量PREV_HASH
中然后在第二次运行时,将使用列表中的新行更新文件。它将包含一个递增的数字,先前的哈希和当前的哈希
2,上一个#,当前#
在删除全局PREV_HASH时,我得到以下输出
>file does not exist
>-----------------
>24
>1--2019-05-31-archive.zip
>what is the chain list at this point:[1, 0, 0]
>1 previous hash is:
>C:\Python>"SL Proof of Concept.py"
>-----------------
>17
>2--2019-05-31-archive.zip
>what is the chain list at this point:[2, '0', '01d056902f77f5a247f639d363b67827d762d72f9738498989d417563c504a3f82f7b44d7e827cd35843545d33856c85']
>2 previous hash before insert is:
>2 what is the chain list at this point:[2, '', '93fcc831b99a8de59063924a994bf81d09dc677b635e32fc133747ca564bfa843fa6bf60274feeb372a5eeb6f406a120', '0', '01d056902f77f5a247f639d363b67827d762d72f9738
498989d417563c504a3f82f7b44d7e827cd35843545d33856c85']
答案 0 :(得分:1)
如果此代码位于文件的顶层,只需删除这些global
语句即可。
如果此代码包含在某些内容内,则需要在第一行的第一行之前放置global
。 (PREV_HASH = ''
)