问题描述
我是一名 Python 初学者,我想执行一个方法 (A),并带有参数,该方法将调用另一个将返回值到 (A) 的方法 (B)。 我只是无法直接到达 (B) 方法,为此我使用了一个 main。所以我无法从(A)中检索(B)的信息 我的架构是这样的:
Main Folder
|-> test_caller.py (A)
|-> called_file.py (B)
我想从 test_caller.py(主方法)调用一个带有参数的方法,该方法将执行到 called_file.py(function_Called())的方法,如果可能的话,我希望 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,"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