使用arguments从另一个python文件执行方法



我是一名python生成工程师,我想执行一个带有arguments的方法(a(,该方法将调用另一个将向(a(返回值的方法(B(。我只是不能直接到达(B(方法,为此我使用了一个main。因此我无法从(A(中检索(B(的信息我的架构是这样的:


Main Folder
|-> test_caller.py (A)
|-> called_file.py (B)

我想从test_caller.py(主方法(调用一个带有arguments的方法,该方法将执行到called_file.py(function_called(((的方法,如果可能的话,我希望该function_called((方法返回标志或值。


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()

called_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

最新更新