Skip to content

Instantly share code, notes, and snippets.

@luliangce
Last active December 24, 2023 12:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luliangce/e587238ed619084cef9ddeeab7d4ece8 to your computer and use it in GitHub Desktop.
Save luliangce/e587238ed619084cef9ddeeab7d4ece8 to your computer and use it in GitHub Desktop.
Stream subprocess stdout to frontend
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.common.dev.js"></script>
</head>
<body>
<div id='app'>
<textarea name="" id="" cols="100" rows="100" v-model="body" disabled></textarea>
</div>
</body>
<script>
const vue = new Vue({
el: '#app',
data() {
return {
body: ''
}
},
mounted() {
this.getData()
},
methods: {
getData() {
fetch('/')
.then(response => {
const reader = response.body.getReader()
let data = []
return reader.read().then(read = (result) => {
if (result.done) {
return data
}
const string = new TextDecoder('utf-8').decode(result.value)
this.body += string
return reader.read().then(read)
})
})
.then(data => {
// Do whatever you want with your data
})
}
}
})
</script>
</html>
import subprocess
from flask import Flask, Response, stream_with_context
from flask import url_for
app = Flask('stream')
@app.route('/')
def stream():
p = subprocess.Popen(
['sh', '-c','ping www.baidu.com'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
@stream_with_context
def generate():
c = 0
while True:
if p.stdout.readable():
yield p.stdout.readline(1024)
c+=1
if c>10:
return
return Response(generate())
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment