简体   繁体   English

在 python 中的 2 个无限循环之间传递数据

[英]Passing data between 2 endless loops in python

I am using a python script which uses cmdloop and takes input from the commandline:我正在使用一个 python 脚本,它使用 cmdloop 并从命令行获取输入:

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.另一个脚本使用 flask 并读取 command.txt 文件并将其(通过 GET 请求)提供给客户端。 It also listens for POSTs of clients that executed this command and posted the output:它还侦听执行此命令并发布 output 的客户端的 POST:

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).我真正想要实现的是拥有一个同时运行 flask 应用程序和 cmdloop 的脚本,只有 cmdloop 显示命令和结果(它来自 flask POST)。 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.通常,在两个脚本/线程/你有什么之间传输数据的最简单方法是使用来自socket库的套接字。 Just have one script/thread host a server bound to 127.0.0.1 and connect to it from the other process!只需让一个脚本/线程托管绑定到 127.0.0.1 的服务器并从另一个进程连接到它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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