Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Run a Python Script from a Rails Application?

I am working on a rails application now that needs to run a single python script whenever a button is clicked on our apps home page. I am trying to figure out a way to have rails run this script, and both of my attempts so far have failed.

My first try was to use the exec(..) command to just run the "python script.py", but when I do this it seems to run the file but terminate the rails server so I would need to manually reboot it each time.

My second try was to install the gem "RubyPython" and attempt from there, but I am at a loss at what to do once I have it running.. I can not find any examples of people using it to run or load a python script.

Any help for this would be appreciated.

like image 598
khalidh Avatar asked Aug 25 '16 05:08

khalidh


2 Answers

Here are ways to execute a shell script

`python pythonscript.py`

or

system( "python pythonscript.py" )

or

exec(" python pythonscript.py")

exec replaces the current process by running the given external command.
Returns none, the current process is replaced and never continues.

like image 113
user7368034 Avatar answered Nov 08 '22 20:11

user7368034


exec replaces the current process with the new one. You want to run it as a subprocess. See When to use each method of launching a subprocess in Ruby for an overview; I suggest using either backticks for a simple process, or popen/popen3 when more control is required.

Alternately, you can use rubypython, the Ruby-Python bridge gem, to execute Python from Ruby itself (especially if you'll be executing the same Python function repeatedly). To do so, you would need to make your script into a proper Python module, start the bridge when the Rails app starts, then use RubyPython.import to get a reference to your module into your Ruby code. The examples on the gem's GitHub page are quite simple, and should be sufficient for your purpose.

like image 40
Amadan Avatar answered Nov 08 '22 19:11

Amadan