在GUI中的容器中运行python脚本

时间:2014-06-12 09:20:19

标签: python multithreading user-interface pyqt multiprocessing

我正在寻找一种在GUI中的容器中运行脚本的方法。

GUI生成一个脚本,我想运行这个脚本而不影响我的GUI。 我的问题是我的脚本中的所有导入和类都在运行后留在内存中并在GUI中生成错误。 是否可以运行脚本,获取结果并删除scrpt运行的所有后果?

我尝试过多处理,线程但它不起作用。我怎样才能做到这一点?非常感谢!

嗨MátyásKuti,我现在只讨论多处理。我想找到一种方法在一个容器中运行它,我可以在脚本停止时删除它。

@pyqtSlot()
def run_func():
    run="""
    import os
    import sys
    from setup import *
    print('toto')
    print('titi')
    """
    from multiprocessing import Pool   
    pool = Pool(processes=4)          
    asyncResult = pool.apply_async(exec(run),{},{}),range(1)    

2 个答案:

答案 0 :(得分:0)

好的,我会向你揭示另一种方法。您可以生成一个包含要执行的代码的临时文件,然后使用subprocess模块将其命令为“python you_script.py”

下一个示例执行一个脚本,该脚本打印输出工作目录中的所有文件。

import os           # Common os operations.
import subprocess   # For creating child processes.
import tempfile     # For generating temporary files.

def make_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


def execute_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)

您可以尝试使用代码中的示例:

@pyqtSlot()
def run_func():
    run="""
    import os
    import sys
    from setup import *
    print('toto')
    print('titi')
    """

    path = make_temp_script(run)
    result, error = execute_external_script(path)

答案 1 :(得分:0)

您可以尝试将脚本编入函数:

script = """
def func():
""" + yourScript
yourGlobals = ...
exec script in yourGlobals
yourGlobals["func"]()

上面的代码只是一般的想法:你必须修复它以缩进yourScript。您的脚本创建的所有全局变量实际上都是func的本地变量,因此将在func返回后删除。可能不会删除导入,包表中将继续有一个条目。

如果上述情况不充分,因为导入没有被清除,也许您可​​以描述错误以及导致错误的导入,可能还有另外一种方法。

如果脚本需要很长时间才能运行,那么上述技术也可以在单独的线程中运行。