我在python文件(parent.py)中有一个parent_app,我试图在另一个python文件(child.py)中的child_app中挂载。 mount似乎可以工作但是,当我尝试通过child_app中的mount挂载来自parent_app的路由时,这条路径似乎无法在我的parent.py文件中使用全局变量。
parent.py文件:
from bottle import route
import bottle
import subprocess as sp
global extProc
parent_app = bottle.Bottle()
@parent_app.route('/start')
def start_bazarr():
global extProc
extProc = sp.Popen(['python','child.py'])
@parent_app.route('/stop')
def stop_bazarr():
sp.Popen.terminate(extProc)
@parent_app.route('/restart')
def restart_bazarr():
stop_bazarr()
start_bazarr()
if __name__ == '__main__':
start_bazarr()
child.py文件:
from bottle import route, run
import bottle
from parent import parent_app
child_app = bottle.Bottle()
@child_app.route('/')
def root():
return u'Lorem Ipsum'
if __name__ == '__main__':
child_app.mount('/power', parent_app)
child_app.run(host='127.0.0.1', port=8080)
我试图致电的网址:
http://127.0.0.1:8080/power/restart
我得到的错误:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\bottle.py", line 862, in _handle
return route.call(**args)
File "C:\Python27\lib\site-packages\bottle.py", line 1740, in wrapper
rv = callback(*a, **ka)
File "C:\Users\morpheus\Desktop\parent.py", line 20, in restart_bazarr
stop_bazarr()
File "C:\Users\morpheus\Desktop\parent.py", line 16, in stop_bazarr
sp.Popen.terminate(extProc)
NameError: global name 'extProc' is not defined
我做错了什么?
答案 0 :(得分:0)
在全局范围内,您不需要global
关键字。您可以定义它,并将其设置为None
作为临时占位符。
from bottle import route
import bottle
import subprocess as sp
extProc = None
terminate
函数需要了解extProc
@parent_app.route('/stop')
def stop_bazarr():
global extProc
sp.Popen.terminate(extProc)