簡體   English   中英

如何從另一個程序在python中調用main函數中的變量?

[英]How to call a variable inside main function from another program in python?

我有兩個python文件first.py和second.py

first.py看起來像

def main():
  #some computation
  first_variable=computation_result

second.py看起來像

import first
def main():
  b=getattr(first, first_variable)
  #computation

但我收到“無屬性”錯誤。 有什么辦法可以通過second.py訪問first.py中main()方法內部的變量?

您應該使用函數調用並返回值,而不要使用它。

從第一個文件中的函數返回Calculation_result,然后將結果存儲在第二個文件中的b變量中。

first.py

def main():
    # computation
    return computation_result

second.py

import first
def main():
    b = first.main()

另一種選擇是在第一個文件中使用全局變量,您將在該文件中存儲該值並稍后引用它。

您將需要閱讀“語言參考”中的“教程和命名與綁定”中的9.1和9.2

在您的示例中, first_variable僅存在於 first.main()的本地范圍內-執行時。 該范圍之外的任何內容都無法訪問它。


您需要將first_variable放入first的全局范圍內-然后在second您可以將它與first.first_variable一起first.first_variable

一種方法是從first.main()返回值並將其分配給first_variable

def main():
    return 2

first_variable = main()

然后在second您可以使用它:

import first
times_3 = first.first_variable * 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM