Reputation: 187
I have a python script that has a method that takes in a string that contains another python script. I'd like to execute that script, call a function in it, and then use that function's results in my main script. It currently looks something like this:
def executePythonScript(self, script, param):
print 'Executing script'
try:
code = compile(script, '<string>', 'exec')
exec code
response = process(param)
except Exception as ex:
print ex
print 'Response: ' + response
return response
The "process" function is assumed to exist in the script that gets compiled and executed run-time.
This solution works well for VERY simple scripts, like:
def process():
return "Hello"
...but I'm having no luck getting more complex scripts to execute. For instance, if my script uses the json package, I get:
global name 'json' is not defined
Additionally, if my process function refers to another function in that same script, I'll get an error there as well:
def process():
return generateResponse()
def generateResponse():
return "Hello"
...gives me an error:
global name 'generateResponse' is not defined
Is this an issue of namespacing? How come json (which is a standard python package) does not get recognized? Any advice would be appreciated!
Upvotes: 1
Views: 185
Reputation: 429
import subprocess
subprocess.call(["python","C:/path/to/my/script.py"])
I would recommend against this and just use import
.
This is also under the assumption that your PYTHONPATH is set in your environment variables.
Upvotes: 1