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:
Class Stuff():
def __init__(self, f):
self.f = f
self.log = {}
def execute(self, filename):
execfile(filename)
if __name__ == '__main__':
#start this script as server
clazz = Stuff()
#here helper_script name will be provided by client at runtime
clazz.execute(helper_script)
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:
import os
a = 3
b = 4
I tried using execfile and subprocess.
Helper scripts, or template modules, are helper files that can make your templates more efficient by performing specific functions. For example, you can use helper scripts to interpret resource metadata, create files, and launch services.
To stop code execution in Python you first need to import the sys object. After this, you can then call the exit() method to stop the program from running.
The most basic and easy way to run a Python script is by using the python command. You need to open a command line and type the word python followed by the path to your script file, like this: python first_script.py Hello World! Then you hit the ENTER button from the keyboard and that's it.
Basic Syntax for Defining a Function in Python In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.
You can pass a locals dictionary to execfile
. After executing the file, this dictionary will contain the local variables it defined.
class Stuff():
def __init__(self):
self.log = {}
def execute(self, filename):
client_locals = {}
execfile(filename, globals(), client_locals)
return client_locals
if __name__ == '__main__':
#start this script as server
clazz = Stuff()
#here helper_script name will be provided by client at runtime
client_locals = clazz.execute('client.py')
print(client_locals)
With your client.py
, this will print:
{'a': 3, 'b': 4, 'os': <module 'os' from '/Users/.../.pyenv/versions/2.7.6/lib/python2.7/os.pyc'>}
A word of warning on execfile
: don't use it with files from untrusted sources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With