2024년 3월 15일 금요일

[python] subprocess

proc.py

import asyncio

from argparse import ArgumentParser

from asyncio import sleep



async def process_function(user, file_path):

    if user == 'user1':

        await sleep(2)

    result = f"Process for user {user}"

    with open(file_path, 'w') as fh:

        fh.write(result)

    print("Hello world")



if __name__ == '__main__':

    parser = ArgumentParser()

    parser.add_argument('--name')

    parser.add_argument('--path')


    args = parser.parse_args()

    user = args.name

    file_path = args.path


    asyncio.run(process_function(user, file_path)


=====================================================

main.py

import asyncio

import subprocess



async def proc(user):

    file_path = f"{user}_output.txt"

    process = subprocess.Popen(['python', 'proc.py', '--name', user, '--path', file_path])

    await asyncio.to_thread(process.wait)


    with open(f"{user}_output.txt", "r") as output_file:

        result = output_file.read()

        print(result)



async def broker():

    users = ['user1', 'user2', 'user3']

    await asyncio.gather(*(proc(user) for user in users))



def main():

    asyncio.run(broker())



if __name__ == "__main__":

    main()



2024년 3월 6일 수요일

[python] tornado 오래 걸리는 작업

 import json

import tornado.ioloop

import tornado.web

from src.exec import Executor



class ShellHandler(tornado.web.RequestHandler):

    async def long_running_task(self):

        """

        get, post 로 호출 시 오래 걸리는 작업.

        """

        executor = Executor()

        stdout, stderr = await executor.run()

        return stdout, stderr


    async def post(self):

        data = self.request.body.decode('utf-8')

        try:

            json_data = json.loads(data)

            self.write(f'received => {json_data}')

        except json.JSONDecodeError:

            self.write(f'error => {data}')


    async def get(self):

        ip_address = self.request.remote_ip

        stdout, stderr = await self.long_running_task()

        self.write(f"{ip_address}<br>stdout={stdout}<br>stdout={stderr}")



def make_app():

    return tornado.web.Application([

        (r"/shell", ShellHandler),

    ])



if __name__ == "__main__":

    app = make_app()

    app.listen(8888)

    print("Server is listening on port 8888")

    tornado.ioloop.IOLoop.current().start()


[python] subprocess

proc.py import asyncio from argparse import ArgumentParser from asyncio import sleep async def process_function(user, file_path):     if use...