我在这里读过很多关于在CGI调用的python脚本中启动另一个python脚本的问题的文章,也就是说,我有一个运行在启用CGI的Raspberrypi上的apache2服务器。
1)从浏览器: webform数据被发送到CGI接口,它调用我的python脚本test1.py
2)在test1.py
中,我想调用test2.py
(它将永远运行或在所需的任何时间内运行(它在某个地方不断更新值)
3)要点是:我想让CGI脚本立即显示一些结果,比如在“结果网页”上说"test2已启动“,并在后台运行我的test2.py
。
然而,发生的事情是,带有表单的网页将永远等待我的test2.py完成!
我尝试过这样的东西:
p = subprocess.Popen([sys.executable, '/var/www/cgi-bin/test2.py'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
但这不起作用(即等待脚本test2完成...)
有人能帮帮忙吗?
发布于 2018-08-05 06:39:46
第一个问题的答案是这个链接。getting start Cgi programmin
第二个问题的答案是:你应该使用多线程编程。
如果您在模块test2中有示例函数...
#in test1.py
import threading
import test2
T1 = threading.Thread(test2.sample(object))
T1.start()
回答你的第三个问题:
然后,您可以在站点的路径中创建一个cgi文件所在的文件夹,或者配置某些目录以将某些文件类型作为cgi脚本进行处理。这在上面的cgi文档中描述得很好,但本质上是为了让cgi文件夹中的所有文件都被执行,您将使用以下apache2:
Options ExecCGI SetHandler cgi-script
要允许.py文件作为脚本在特定文件夹中执行,您可以使用以下配置文件:
<Directory /srv/www/yoursite/public_html>
Options +ExecCGI
AddHandler cgi-script .py
</Directory>
一旦你有了它,如果你运行的是python3,你可以创建一个像这样的python脚本,并把它放在为cgi配置的任何文件夹中:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-# enable debugging
import cgitb
cgitb.enable() print("Content-Type: text/html;charset=utf-8")
print() print("Hello World!")
发布于 2018-08-05 06:57:12
谢谢,这是一个很好的回答!
我只是在我的脚本test1.py中添加了这段代码(在test2.py中没有函数,只是原始代码):
..。导入test2 cgitb.enable()
T1 = threading.Thread(test2) T1.start()
..。
然而,网页仍然永远等待,尽管我注意到test2确实是由线程启动的……你知道如何让网页显示一些东西而不是等待吗?
请注意,我也尝试过:
pid = os.fork()
#if pid==0 then we are in the child process
if(pid==0):
T1 = threading.Thread(test2)
T1.start()
#i would hope that here the child process is detached from making wait the CGI!! but no
else:
print('Content-type: text/html\n\n')
print('<h1>Python Script Test</h1>')
form = cgi.FieldStorage()
tempThVal = form['tempThresh'].value
print('Temperature threshold= ' + tempThVal)
但该死的浏览器仍在等待它的结束!!
发布于 2018-08-05 07:26:56
要解决这个问题,您可以将您自己的解决方案与我的答案结合起来,以获得正确的答案。
#in test1.py
class my_thread(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
p = subprocess.Popen([sys.executable, '/var/www/cgi-bin/test2.py'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
########################
#or your test2 statment#
########################
pid = os.fork()
#if pid==0 then we are in the child process
if(pid==0):
T1 = my_thread()
T1.start()
#i would hope that here the child process is detached from making wait the CGI!! but
no
else:
print('Content-type: text/html\n\n')
print('<h1>Python Script Test</h1>')
form = cgi.FieldStorage()
tempThVal = form['tempThresh'].value
print('Temperature threshold= ' + tempThVal)
我在Django框架中使用了这种方法来解决这个问题
https://stackoverflow.com/questions/51689867
复制相似问题