【问题标题】:Run Python script from another and pass the variables and output从另一个运行 Python 脚本并传递变量和输出
【发布时间】:2015-10-06 17:50:44
【问题描述】:

在寻找有关在 Python 脚本之间传递变量和输出的教程时,我在我的示例中找不到任何适用于 WSGI 服务器的示例。

我希望 输出(和变量) 以 HTML 形式返回,而不是仅在控制台中查看。

我发现从另一个调用 python 脚本的最佳解决方案是 subprocess,但我仍然无法在我的 Web 浏览器中看到 Script 1 和 Script 2 的合并输出,并且只能在控制台中看到。

脚本 1:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from cgi import escape
import sys, os
from flup.server.fcgi import WSGIServer
import subprocess

def app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])

    yield '<h1>Test - Python pass output and variables</h1>'
    yield '<p>Script 1</p>'
    yield subprocess.check_output(["python", "script2.py"])

WSGIServer(app).run()

脚本 2:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

print "<p>Script 2</p>";

【问题讨论】:

  • 我认为从 Web 服务器调用一些脚本不是一个好主意。加载时间可能会增加,因此没有人会等待内容加载。
  • 页面加载后调用脚本。它处于模板阶段,唯一的目的是处理来自表单的输入。

标签: python apache fastcgi wsgi fcgid


【解决方案1】:

如果你想在 python 中的脚本之间传递变量,请执行以下操作:

Script1.py:

def passVars():
    variable = "bla"
    return variable

Script2.py:

import Script1 as sc1

var = sc1.passVars()

【讨论】:

  • 当我将它作为独立脚本运行时工作正常,但不能在 WSGIServer 的 app 方法中运行。
  • 这可以工作:在脚本目录中创建一个文本文件和: script1.py: f = open("./a.txt", "w") f.write(variable) /// //// appmethod.py: f = open("./a.txt", "r") var = f.read()
  • 最终它在运行代码示例时工作,但我接受你的两种解决方案。
猜你喜欢
  • 2015-09-14
  • 2021-08-04
  • 2020-09-02
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 2014-07-01
相关资源
最近更新 更多