Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to return data from one python file to another

Tags:

python

I have a python script which defines step to take in an experiment definition.py, and another python script which executes the experiment execute.py. The first file I want to think of as data moreso than code; when an experiment is executed a folder is created for it, definition.py is moved into the folder, and any data generated from the experiment is saved there as well.

I intend to call execute.py like

execute.py -f save_stuff_here -d this_is_the_definition.py

but I'm not sure what the best way to accomplish this is. Other questions on stackoverflow have suggested importing the definition, but I don't think that will work for me. I have no assurance that the definition is somewhere in the PYTHONPATH, nor that the definition has the same name. I'd prefer it need not be, as the user should be providing that information.

The definition.py needs to define a single object (a list of actions), and execute.py needs to be able to refer to the object.

The ideal behaviour I would like is that script1.py path/to/script2.py return a value from script2.py to script1.py, where path/to/script2.py is any arbitrary file.

Can it be done?

like image 808
Malcolm Gooding Avatar asked Oct 22 '22 05:10

Malcolm Gooding


2 Answers

execfile the file with an explicit globals dict. You can get at anything defined in the file by reading the globals dict. If you need Python 3 compatibility, you can open the file, read the contents, and exec them.

like image 83
user2357112 supports Monica Avatar answered Oct 30 '22 00:10

user2357112 supports Monica


Do you need send data from path/to/script2.py to script1.py once the script2.py finish to run? Did you try..?

script2.py

import os
data = "whatever"
os.system("python ..//..//script1.py %s" % data)

script1.py

import sys
data = sys.argv[1]
print "my data is: " + data
raw_input('enter to finish')
like image 44
ger84 Avatar answered Oct 29 '22 22:10

ger84