简体   繁体   中英

Is it possible to redirect the python output to web by using 'sys.stdout' command?

Is it possible to redirect the python output to web by using the redirecting command? I know that we can redirect the output like this

import sys
sys.stdout = open('file', 'w')
print 'test'

or

In terminal like this

$ python foo.py > file

I heard the 'Django' and 'Flask' like web framework can do the trick. I wonder whether by using a simple command like sys.stdout can redirect the output to web?

One cool trick you can do as a quick-and-dirty hack to quickly access the output of your python script from the web is redirect it to nc with the -l (listen) option, like this:

python foo.py | nc -l 8080

You can then go to localhost:8080 in your web browser to see the output. It's not really a web server though -- it only works one time, Once someone loads the page. it will stop serving requests.

As a slightly more advanced variant of this that allows visiting the page more than once, wrap it in a loop, something like:

while true; do python foo.py | nc -l 8080; done

That'll re-run your script every time you refresh the page though, As one final layer of sophistication: you can cache the result so it doesn't need to be recomputed each time:

python foo.py > /tmp/myoutput; while true; do nc -l 8080 < /tmp/myoutput; done

Obviously none of these are real production-quality solutions, you should use a proper web framework like Flask etc., but they can do the trick if you just want to quickly test something out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM