我有一個python cgi腳本,用於檢查進程是否處於活動狀態,如果未找到該進程,則啓動它。該進程本身是一個網絡服務器(基於web.py)。確保該進程正在運行後,我嘗試向其發送url請求。這個想法是將這個請求的結果重定向到我的cgi腳本的請求者,基本上我想將查詢重定向到偵聽不同端口的本地webserver。從cgi腳本中調用urlopen'連接被拒絕'錯誤
如果我先從服務器啓動服務器(findImgServerProcess返回True),則不使用cgi請求,此代碼正常工作。但是,如果我嘗試通過下面的cgi腳本啓動進程,則確實會得到urllib2.urlopen調用,這會引發連接被拒絕的異常。 我不明白爲什麼? 如果我打印進程列表(在findImgServerProcess()
),我可以看到進程在那裏,但爲什麼urllib2.urlopen會拋出異常?我有apache2 webserver設置爲使用suexec。
下面的代碼:
#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
import os, re
import sys
import subprocess
import urllib2
urlbase = "http://localhost:8080/getimage"
imgserver = "/home/martin/public_html/cgi-bin/stlimgservermirror.py" # this is based on web.py
def findImgServerProcess():
r = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
return re.match(".*%s" % os.path.split(imgserver)[-1], r, re.DOTALL)
def ensureImgServerProcess():
if findImgServerProcess():
return True
os.environ['LD_LIBRARY_PATH'] = '/home/martin/lib'
fout = open("/dev/null", "w")
ferr = fout
subprocess.Popen([sys.executable, imgserver], stdout=fout, stderr=subprocess.STDOUT)
# now try and find the process
return findImgServerProcess() != None
def main():
if not ensureImgServerProcess():
print "Content-type: text/plain\n"
print "image server down!"
return
form = cgi.FieldStorage()
if form.has_key("debug"):
print "Content-type: text/plain\n"
print os.environ['QUERY_STRING']
else:
try:
img = urllib2.urlopen("%s?%s" % (urlbase, os.environ['QUERY_STRING'])).read()
except Exception, e:
print "Content-type: text/plain\n"
print e
sys.exit()
print "Content-type: image/png\n"
print img
if __name__ == "__main__":
main()