python-3.x 将变量从file1.py中的函数导入到file2.py

vshtjzan  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(96)

我有一个名为file1.py的python文件,它有以下功能:

def randomize_alt(res,start):
    seed=start
    need=''
    while len(need)!=352:
        if seed>=len(res):
            seed=start+1
        need+=res[seed]
        seed+=2
    return need

def generate_keys(user):
    original_hash = keccak.get_hash_of(user.encode('utf-8')) 
    res=original_hash.decode('utf-8')
    print(f"Some Output: {res}")
    want=randomize_alt(res,0)
    print("\nThe alternate bits the output: ",want)
    ind=0;ans=[];tmp=[]
    cnt=0
    keys=[]
    while ind<352:
        string=want[ind:ind+2]
        ind+=2
        tmp.append(int(string,16))
        if ind%8==0:
            ans.append(tmp)
            tmp=[]
            cnt=cnt+1
        if cnt==4:
            keys.append(ans)
            cnt=0
            ans=[]
    return keys

字符串
现在,我有另一个名为file2.py的文件,其内容如下:

from file1 import *
from file1 import generate_keys
get_keys = generate_keys("SomeInput")
print(f"\n\nThe generated keys for SomeInput are: {get_keys}")
#get first 32 characters of the string obtained
key = generate_keys("Pars03")
print(len(want))


现在,我需要在file1.py中使用generate_keys中的want变量。
我尝试了下面的事情:

from file1 import *
from file1 import generate_keys


它给了我以下错误:AttributeError: 'function' object has no attribute 'want'
我不知道我哪里错了。

EDIT 1:我将want变量声明为global,并在generate_keys函数之外。

现在,file1want的长度是正确的,但在file2中,它的长度是0,这意味着它将其视为空字符串。

vcirk6k6

vcirk6k61#

第一次修正

file1.py

want = ""     <---- define want outside of generate_keys()

def generate_keys(user):
    global want      <----- Use global for want
    
    # your code
    ...

    return keys

字符串

第二次修正

file2.py中,您必须更改指令from file1 import *并导入模块file1

#from file1 import *    <---- remove this import
import file1        # <------------ add this import
from file1 import generate_keys

get_keys = generate_keys("SomeInput")
print(f"\n\nThe generated keys for SomeInput are: {get_keys}")
#get first 32 characters of the string obtained
#key = generate_keys("Pars03").want[:32]   <------ THIS IS YOUR wrong code
print(file1.want[:32])  #<----- change want[:32] to file1.want[:32]

其他解决方案

另一种解决问题的方法是保持file1.py的代码不变,但通过调用函数generate_keys()返回want:

def randomize_alt(res,start):
    # your code
    ...

def generate_keys(user):
    # your code
    ...
    return keys, want


在这种情况下,不需要在generate_keys()之外声明want,也不需要使用关键字global
file2.py变为如下:

from file1 import generate_keys

get_keys = generate_keys("SomeInput")
print(f"\n\nThe generated keys for SomeInput are: {get_keys}")
#get first 32 characters of the string obtained
key, want = generate_keys("Pars03") # <----- generate_keys() returns key and want
print("want = \'" + want[:32]  + "\'")

相关问题