简体   繁体   中英

Error in importing variables from one python script to another python script

I have a set of more than 10 variables defined in __main__ of one python script and they are needed to import into another python script to use their values inside different methods. I used from <pythonfile> import var1, var2 ...., var10 in the calling python script but it is giving me error like below:-

ImportError: cannot import name 'envName'

Sample structure of my A.py and B.py scripts are like this:- A.py

if __name__ == '__main__':
    var1 = "text1"
    var2 = "text2"
    var3 = "text3"
    B.methodA()

B.py

from A import var1, var2, var3

def methodA()
    print(var1)

This is something I am looking for. Basically I have like more than 10 variables to use in another script (both scripts are in same folder) so need some help to find out the best way to do it. I know the process above I am using could be very stupid and wrong.

Can anyone please help me? I am using python3.6 Also what is the best way to import and use these many variables from one python script into another python script?

Assuming you mean that by defining the variables "in __main__ " you mean you have something like:

if __name__ == '__main__':
    var1 = 'foo'

then you can't directly import var1 into another script. __name__ is only '__main__' if the file is being run directly. If you're importing it into another script __name__ is not '__main__' so the variables are never defined. Simply taking var1 = 'foo' out of if __name__ == '__main__' should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM