呃,这标题有点拗口。举个例子:
使用 Flask-Script 在命令行中执行 python manger.py startcelery
其中 startcelery
是想在 bash 中运行 celery -A celeryd worker -P eventlet -c 1000 -l info
命令。
那么,如何持续获得这条命令的输出内容并显示在 shell 中呢?
附:以上只是举个例子。不要说为什么不直接在 shell 中执行,我只是想把日常开发中所有的行为都放在 manger.py 中集中管理。另外,我也知道可以用 Fabric 完成。。。。可,Py3k ~(>_<)~
下面是套用flask-script
中的逻辑
@app.command def startcelery(): with app.app_context() as ctx: ctx.app.extensions['celery'].worker_main(['worker', '--loglevel=INFO'])
其实celery
提供了一个execute_from_commandline
方法,题主可以研究看看
其实你的需求只需要执行那句命令就可以了,不重定向的话输出会继承 Python 程序的,也就是输出到终端。subprocess.call
、os.system
、os.exec*
都可以满足需求。你根本不需要获得命令的输出。
除了 os.system
外,其它都不涉及到 bash / sh。不要以为只有 bash / sh 这些 shell 才能执行命令。
可以用 subprocess.Popen(..., stdout=PIPE, ...) 来封装命令的内容,这样可以从Popen.stdout读取命令的输出, 比如Popen.stdout.readlines()