[英]Execute method from another python file with argues
我是一個 python 初學者,我想執行一個方法 (A),其中的爭論將調用另一個方法 (B),它將值返回到 (A)。 我只是無法直接到達(B)方法,為此我使用了 main. 所以我無法從 (A) 中檢索 (B) 的信息 我的架構如下所示:
Main Folder
|-> test_caller.py (A)
|-> called_file.py (B)
我想從 test_caller.py(main 方法)調用一個帶有爭論的方法,它將執行方法到 called_file.py(function_call()),如果可能的話,我希望 function_caller() 方法返回標志或值。
test_caller.py:
import sys
import subprocess
import os
def main():
#method can't return something
# my_path = os.path.join(os.path.abspath(__file__+"/../"),"test.py")
# script_descriptor = open(my_path)
# a_script = script_descriptor.read()
# sys.argv = [my_path, "variable1","https://google.com"]
# exec(a_script)
my_path = os.path.join(os.path.abspath(__file__+"/../"),"test.py")
#call function tes.py, but need a main method and so doesn't return the function value yet
test = subprocess.run(['python',my_path,"variable1","https://google.com"],check=True)
print(test)
if __name__ == '__main__':
main()
稱為_file.py:
import sys
import requests
def function_called(variable,variable2):
#Potato = Flag
try :
potato = 0
print(str(variable + " is ready to use "+ variable2 + " as variable number 2"))
request = requests.get(variable2)
if(request.status_code == 200):
response = request.text
return response
else :
potato = 1
#Flag exception potato = 1 => failure
except Exception as exc :
print("An error occured " + str(exc))
potato = 1
return potato
#I want that main issue disappear, for returning potato method value (flag 0 or 1) to my method's calling
# if __name__ == "__main__":
# function_called(sys.argv[1],sys.argv[2])
我怎么能那樣做? 謝謝你幫助我。
您好 AKX 感謝您的幫助,這個解決方案可能對我們的程序有好處,對於那些遇到類似問題的人,現在的解決方案是這樣的:
在 test_caller.py 上:
def main():
test = importlib.import_module("called_file")
object = test.function_called("tata","https://www.google.com")
print(object) #do what you want from the returned object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.