【问题标题】:Run python script in a container in a GUI在 GUI 的容器中运行 python 脚本
【发布时间】:2014-08-02 13:31:54
【问题描述】:

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

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

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

嗨,Mátyás Kuti,我现在只是处理多处理的案例。我想找到一种在脚本停止时可以删除的容器中运行它的方法。

@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)    

【问题讨论】:

  • 您能否提供一些代码,展示您如何尝试使用线程?
  • @user3393374 您应该编辑您的问题并包含该示例代码。它在评论中不可读。

标签: python multithreading user-interface pyqt multiprocessing


【解决方案1】:

好的,我将向您展示另一种方法。您可以生成一个包含您要执行的代码的临时文件,然后使用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)

【讨论】:

  • 谢谢你的回答,我会尽力让你知道的。
【解决方案2】:

你可以试着把脚本变成一个函数:

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

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

如果由于没有清除导入而导致上述内容不充分,也许您可​​以描述错误以及导致错误的剩余导入,可能还有另一种解决方法。

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

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2020-12-31
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多