How to integrate a standalone Python script into a Rails application?

后端 未结 5 2200
你的背包
你的背包 2020-12-24 06:05

I\'ve got a program that has a small file structure going on and is then ran using

python do_work.py foo bar

I want my Rails users to press

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-24 06:45

    I would do something like the following.

    Asynchronously execute this task in the background. And once the result is ready report it to the user.

    One way you can achieve this will by using Open3 and delayed_job gem.

    Take a look the popen3 method in Open3 module.

    Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
      pid = wait_thr.pid # pid of the started process.
      ...
      exit_status = wait_thr.value # Process::Status object returned.
    }
    

    In your case you can change the Open3.popen3 statement to something like the following

    Open3.popen3("python do_work.py foo bar"){
      ...
      # mechanism for reporting like setting a flag in database system
      # or queue system
    }
    

    Note: you should give the full path to your python script

    And then use delayed_job gem to run this as a background task.

    You should also have a polling mechanism which will poll the system to see if the flag is set which would mean the result is ready and then serve it to the user.

提交回复
热议问题