Skip to content
Advertisement

Retain environment of helper python script in main script

I’ve one helper script which I want to call from main script which is acting as a Server. This main script looks like this:

JavaScript

Now Client will invoke this helper script by providing it’s name to main script(Server). After execution I want to retain variables of helper script (i.e: a,b) in main script. I know one way is to return those variables from helper script to main script. But is there any other way so to retain all variables of helper script. This is how helper script looks like:

JavaScript

I tried using execfile and subprocess.

Advertisement

Answer

You can pass a locals dictionary to execfile. After executing the file, this dictionary will contain the local variables it defined.

JavaScript

With your client.py, this will print:

JavaScript

A word of warning on execfile: don’t use it with files from untrusted sources.

Advertisement