9

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.

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.