简体   繁体   English

将变量从一个python脚本导入到另一个python脚本时出错

[英]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. 我在一个python脚本的__main__中定义了一组超过10个变量,需要将它们导入另一个python脚本以在不同方法中使用它们的值。 I used from <pythonfile> import var1, var2 ...., var10 in the calling python script but it is giving me error like below:- 我在调用python脚本中from <pythonfile> import var1, var2 ...., var10 ,但它给了我如下错误:

ImportError: cannot import name 'envName'

Sample structure of my A.py and B.py scripts are like this:- A.py 我的A.py和B.py脚本的示例结构如下:-A.py

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

B.py 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. 基本上,我想在另一个脚本中使用10个以上的变量(两个脚本都在同一文件夹中),因此需要一些帮助以找出实现此目的的最佳方法。 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? 我正在使用python3.6也是从一个python脚本导入和使用这些许多变量到另一个python脚本的最佳方法是什么?

Assuming you mean that by defining the variables "in __main__ " you mean you have something like: 假设您的意思是通过在__main__定义变量,您的意思是:

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

then you can't directly import var1 into another script. 那么您将无法直接将var1导入另一个脚本。 __name__ is only '__main__' if the file is being run directly. 如果直接运行文件,则__name__仅是'__main__' If you're importing it into another script __name__ is not '__main__' so the variables are never defined. 如果将其导入另一个脚本__name__不是'__main__' ,则永远不会定义变量。 Simply taking var1 = 'foo' out of if __name__ == '__main__' should solve your problem. 只需从if __name__ == '__main__' var1 = 'foo'删除var1 = 'foo'就可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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