How to embed a Python interpreter in a PyQT widget

后端 未结 5 1978
忘掉有多难
忘掉有多难 2020-11-29 00:49

I want to be able to bring up an interactive python terminal from my python application. Some, but not all, variables in my program needs to be exposed to the interpreter.

5条回答
  •  无人及你
    2020-11-29 01:27

    Not sure of what you want exactly but have tried to save the widget content into a a temporary file and pass it to a standard python interpreter with Popen ?

    Doc is here : http://docs.python.org/release/2.6.5/library/subprocess.html#subprocess.Popen

    Example :

    import tempfile, os, sys, subprocess
    
    # get the code
    code = get_widget_content()
    
    # save the code to a temporary file
    file_handle, file_path = tempfile.mkstemp()
    tmp_file = os.fdopen(file_handle, 'w')
    tmp_file.write(code)
    tmp_file.close()
    
    #execute it
    p = subprocess.Popen([sys.executable, file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    # wait for the command to complete 
    p.wait()
    
    # retrieve the output:
    pyerr = p.stderr.readlines()
    pyout = p.stdout.readlines()
    
    # do what ever you want with it
    print(pyerr)
    print(pyout)
    

提交回复
热议问题