【问题标题】:Python: How to write to read and write to a global variablePython:如何写入读取和写入全局变量
【发布时间】:2019-05-31 15:00:48
【问题描述】:

尝试从 if/else 语句中读取和写入全局变量但出现错误

SyntaxError: name 'PREV_HASH' is assigned to before global declaration

我已尝试使用全局语法,但无法正常工作。不习惯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']

【问题讨论】:

  • 这里根本没有嵌套作用域。只需摆脱 global ... 行。
  • 不需要global。您已经在顶部定义了它...
  • 当您尝试从函数内部访问变量时,只需将变量标识为global。你这里没有任何函数,只有顶层代码。
  • 全局变量不存储状态在单独的调用之间。您需要将该变量的值写入文件并从那里读回,或者类似的东西那个。
  • @JohnGordon:从函数访问变量时,您不需要将变量定义为global。只有当您尝试从函数中更改变量时,您才需要这样做。

标签: python variables global local


【解决方案1】:

如果此代码位于文件的顶层,只需删除这些 global 语句即可。

如果此代码包含在某些内容中,您需要将global 放在第一个赋值之前的第一行。 (PREV_HASH = '')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-24
    • 2016-10-06
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多