Returns values ​​from one script to another script

I have the following script that will run each script (sequentially) in a directory:

import os directory = [] for dirpath, dirnames, filenames in os.walk("path\to\scripts"): for filename in [f for f in filenames if f.endswith(".py")]: directory.append(os.path.join(dirpath, filename)) for entry in directory: execfile(entry) print x 

my scripts look like this:

 def script1(): x = "script 1 ran" return x script1() 

When print x is called, it says x is undefined. I'm just wondering if there is a way to return the values ​​so that the parent script can access the data.

+3
source share
3 answers

I'm just wondering if there is a way to return the values ​​so that the parent script can access the data.

This is why you define functions and return values.

Script 1 should include a feature.

 def main(): all the various bits of script 1 except the import return x if __name__ == "__main__": x= main() print( x ) 

Works just like yours, but can now be used elsewhere

Script 2 does this.

 import script1 print script1.main() 

That one script uses another.

+7
source

You can use the locals argument for execfile (). Write the scripts as follows:

 def run_script(): ret_value = 2 return ret_value script_ret = run_script() 

And in your main script:

 script_locals = dict() execfile("path/to/script", dict(), script_locals) print(script_locals["script_ret"]) 
+3
source

x is local to the script1 function, so it does not appear in the outer scope. If you put the code inside script1 at the top level of the file, it should work.

+1
source

Source: https://habr.com/ru/post/1483675/


All Articles