您的位置:首页 > 编程语言 > Python开发

python调用子进程实例,来自cherrypy-cgiserver

2013-12-03 15:57 351 查看
python调用子进程实例,调用php-cgi.exe,生成网页内容,截取自cherrypy-cgiserver

import subprocess
import tempfile
from cStringIO import StringIO
import threading
PHP_CGI = 'H:/web/php_server_simple/php/php-cgi.exe'
def test2():
    response = tempfile.SpooledTemporaryFile(
            max_size =1024*1024,
            mode = "w+b"
        )
    handler_executable=PHP_CGI
    cmd_args=[handler_executable,"phpinfo.php"]
    dir="H:/web/django-php-master"
    proc = subprocess.Popen(
            cmd_args,
            executable = handler_executable,
            stdin = subprocess.PIPE,
            stdout = response,
            stderr = subprocess.STDOUT,
            cwd = dir
        )
    proc.force_terminated = False
    body_file = StringIO()
    proc.stdin.write(body_file.read())
    def terminate_cgi_process():
            """
            Terminiert nach einem Timeout den CGI-Prozess
            """

            proc.terminate()
            proc.force_terminated = True
    # Timeout-Timer starten, der nach Ablauf den CGI-Prozess terminiert
    timer = threading.Timer(5, terminate_cgi_process)
    timer.start()

    # Los geht's (hier wird gewartet bis das CGI-Programm fertig ist)
    proc.communicate()

    # Timeout-Timer abbrechen, da er hier nicht mehr ben?tigt wird
    timer.cancel()

    # Falls der Timeout-Timer den CGI-Prozess abbrechen musste, wird der
    # GATEWAY_TIMEOUT-Fehler ausgel?st.
    if proc.force_terminated:
        raise cherrypy.HTTPError(httplib.GATEWAY_TIMEOUT)

    # Get header lines
    response.seek(0)
    print response.read()
if __name__=="__main__" :
    test2()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: