2 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
這樣的事情應(yīng)該有助于恕我直言
import shlex
import subprocess
def get_output(command, working_folder=None):
logging.debug("Executing %s in %s", command, working_folder)
try:
output = subprocess.check_output(shlex.split(command), cwd=working_folder)
return output.decode("utf-8")
except OSError:
logging.error("Command being executed: {}".format(command))
raise

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
實(shí)際上,我剛剛記得一個(gè)更好的解決方案是使用異步消息隊(duì)列庫(kù)。我熟悉的并且很容易適應(yīng)的是 ZMQ https://zeromq.org/。使用 Go 腳本作為服務(wù)器偵聽(tīng)和 django 應(yīng)用程序請(qǐng)求作為作業(yè)的客戶(hù)端來(lái)進(jìn)行服務(wù)器/客戶(hù)端設(shè)置非常容易。
作為概念證明,這里是來(lái)自不同庫(kù)文檔的片段。
GO中的服務(wù)器
這個(gè)腳本就是服務(wù)端,用Go寫(xiě)的,我相信可以設(shè)置成服務(wù)持續(xù)運(yùn)行,等待django發(fā)送job來(lái)做。
// source: https://github.com/pebbe/zmq4/blob/master/examples/hwserver.go
//
// Hello World server.
// Binds REP socket to tcp://*:5555
// Expects "Hello" from client, replies with "World"
//
package main
import (
zmq "github.com/pebbe/zmq4"
"fmt"
"time"
)
func main() {
// Socket to talk to clients
responder, _ := zmq.NewSocket(zmq.REP)
defer responder.Close()
responder.Bind("tcp://*:5555")
for {
// Wait for next request from client
msg, _ := responder.Recv(0)
fmt.Println("Received ", msg)
// Do some 'work', can take a whilst
time.Sleep(time.Second)
// Send reply back to client
reply := "World"
responder.Send(reply, 0)
fmt.Println("Sent ", reply)
}
}
python中的客戶(hù)端
這是可以在任何 http 請(qǐng)求中輕松調(diào)用的 python 應(yīng)用程序。它可以創(chuàng)建 zmq 上下文并開(kāi)始向 go 服務(wù)器發(fā)送要做的事情。
# source: http://zguide.zeromq.org/py:hwclient
#
# Hello World client in Python
# Connects REQ socket to tcp://localhost:5555
# Sends "Hello" to server, expects "World" back
#
import zmq
context = zmq.Context()
# Socket to talk to server
print("Connecting to hello world server…")
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")
# Do 10 requests, waiting each time for a response
for request in range(10):
print("Sending request %s …" % request)
socket.send(b"Hello")
# Get the reply.
message = socket.recv()
print("Received reply %s [ %s ]" % (request, message))
# Gracefully closing the sockects
socket.close()
context.term()
# Back to normal django stuff
這種方法的創(chuàng)建是客戶(hù)端可以動(dòng)態(tài)創(chuàng)建和關(guān)閉 zmq 上下文。此外,您甚至不必在同一臺(tái)服務(wù)器上運(yùn)行 go 腳本。您可以與任何 IP 地址進(jìn)行通信。如果您注意至少對(duì)包進(jìn)行加密,請(qǐng)查看 ZMQ 提供的安全功能。
--
注意:我知道我在回答我自己的問(wèn)題,但這就像給 IT 打電話(huà)一樣,您需要在他們接電話(huà)時(shí)立即給他們打電話(huà)以解決問(wèn)題
- 2 回答
- 0 關(guān)注
- 126 瀏覽
添加回答
舉報(bào)