[英]How to call a variable inside main function from another program in python?
I have two python files first.py and second.py 我有两个python文件first.py和second.py
first.py looks like first.py看起来像
def main():
#some computation
first_variable=computation_result
second.py looks like second.py看起来像
import first
def main():
b=getattr(first, first_variable)
#computation
but I am getting No Attribute error. 但我收到“无属性”错误。 Is there any way to access a variable inside main() method in first.py through second.py? 有什么办法可以通过second.py访问first.py中main()方法内部的变量?
You should use function calls and return values instead of this. 您应该使用函数调用并返回值,而不要使用它。
Return the computation_result from the function in the first file, and then store the result in the b variable in the second file. 从第一个文件中的函数返回Calculation_result,然后将结果存储在第二个文件中的b变量中。
first.py first.py
def main():
# computation
return computation_result
second.py second.py
import first
def main():
b = first.main()
Other option is to use a global variable in the first file where you will store the value and later reference it. 另一种选择是在第一个文件中使用全局变量,您将在该文件中存储该值并稍后引用它。
You will want to read 9.1 and 9.2 in the Tutorial and Naming and Binding in the Language Reference. 您将需要阅读“语言参考”中的“教程和命名与绑定”中的9.1和9.2 。
In your example first_variable
only exists within first.main()
's local scope - while it is executing. 在您的示例中, first_variable
仅存在于 first.main()
的本地范围内-执行时。 It isn't accessible to anything outside of that scope. 该范围之外的任何内容都无法访问它。
You need to get first_variable
into first
's global scope - then in second
you can use it with first.first_variable
. 您需要将first_variable
放入first
的全局范围内-然后在second
您可以将它与first.first_variable
一起first.first_variable
。
One way would be to return something from first.main()
and assign it to first_variable
. 一种方法是从first.main()
返回值并将其分配给first_variable
。
def main():
return 2
first_variable = main()
Then in second
you can use it: 然后在second
您可以使用它:
import first
times_3 = first.first_variable * 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.