Run Python Script In A Container In A Gui
Solution 1:
Ok, I will expose to you another approach. You can generate a temporary file wich contain the code you want to execute, and then use subprocess module for excecute it with the command "python you_script.py"
The next example execute an script that prints to output all the files an directories in the working dir.
import os # Common os operations.import subprocess # For creating child processes.import tempfile # For generating temporary files.defmake_temp_script(script):
"""
Creates a temp file with the format *.py containing the script code.
Returns the full path to the temp file.
"""# Get the directory used for temporaries in your platform.
temp_dir = os.environ['TEMP']
# Create the script.
_ , path = tempfile.mkstemp(suffix=".py", dir=temp_dir)
fd = open(path, "w")
fd.write(script)
fd.close()
return path
defexecute_external_script(path):
"""
Execute an external script.
Returns a 2-tuple with the output and the error.
"""
p = subprocess.Popen(["python", path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return (out, err)
if __name__ == '__main__':
script = \
"""
import os
import sys
print(os.listdir())
"""
path = make_temp_script(script)
out, err = execute_external_script(path)
print(out)
print(err)
You can try something like the example in your code:
@pyqtSlot()defrun_func():
run="""
import os
import sys
from setup import *
print('toto')
print('titi')
"""
path = make_temp_script(run)
result, error = execute_external_script(path)
Solution 2:
You could try making the script into a function:
script = """
def func():
""" + yourScript
yourGlobals = ...
exec script in yourGlobals
yourGlobals["func"]()
The above code is just the general idea: you will have to fix it to indent yourScript
. All globals created by your script will in fact be locals to func
so will be removed after func
returns. The imports will probably not be removed, there will continue to be an entry in the package table.
If the above is not sufficient because imports don't get purged, perhaps you can describe the error and what imports are left that cause error, may be there is another way around this.
If the script can take a long time to run then the above technique can work in a separate thread too.
Post a Comment for "Run Python Script In A Container In A Gui"