Communication between two python scripts

前端 未结 3 2054
执笔经年
执笔经年 2020-12-03 03:18

a methodology question:

I have a \"main\" python script which runs on an infinite loop on my system, and I want to send information to it (a json data string for exa

3条回答
  •  既然无缘
    2020-12-03 04:09

    Since the "main" script looks like a service you can enhance it with a web API. bottle is the perfect solution for this. With this additional code your python script is able to receive requests and process them:

    import json
    
    from bottle import run, post, request, response
    
    @post('/process')
    def my_process():
      req_obj = json.loads(request.body.read())
      # do something with req_obj
      # ...
      return 'All done'
    
    run(host='localhost', port=8080, debug=True)
    

    The client script may use the httplib to send a message to the server and read the response:

    import httplib
    
    c = httplib.HTTPConnection('localhost', 8080)
    c.request('POST', '/process', '{}')
    doc = c.getresponse().read()
    print doc
    # 'All done'
    

提交回复
热议问题