简体   繁体   中英

Passing data between 2 endless loops in python

I am using a python script which uses cmdloop and takes input from the commandline:

import cmd


class SuperC2(cmd.Cmd):
    def default(self, line):
        f = open("command.txt", "w")
        f.write(line)
        f.close()


if __name__ == '__main__':
    SuperC2().cmdloop('Shell')

Another script uses flask and reads the command.txt file and serves it (via GET request) to a client. It also listens for POSTs of clients that executed this command and posted the output:

from flask import Flask
from flask import request

app = Flask(__name__)


@app.route('/command')
def command():
    str = open('command.txt', 'r').read()
    return str

@app.route('/result', methods = ['POST'])
def result():

    if request.method == 'POST':
        data = request.form
        print(data["command"])
        print(data["output"])
    return "ok"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)

What I really would like to achieve is to have 1 script that runs the flask app and the cmdloop at the same time, with only the cmdloop showing the command and the result (it got from the flask POSTs). Can someone give an example on how it can be done? I'm guessing Process Queues or pipes?

Generally, the simplest way to transfer data between two scripts/threads/what have you is to use a socket from the socket library. Just have one script/thread host a server bound to 127.0.0.1 and connect to it from the other process!

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