20

For example, I can use Python scripts in PHP like there:

exec("python script.py params",$result);

where "script.py" - script name and variable $result save output data.

How I can make it with Ruby? I mean, call Python scripts from Ruby.

1

5 Answers 5

31

You can shell-out to any shell binary and capture the response with backticks:

result = `python script.py params`
Sign up to request clarification or add additional context in comments.

Comments

11

One way would be exec.

result = exec("python script.py params")

2 Comments

I think it may be worth noting that using the exec function will replace the current running process with the command supplied. If, like me, you're looking for a way to invoke a helping shell command and capture the result, you should use another method (i.e. "maniacalrobot"'s answer below).
Using exec() will end the current process once running the python script is accomplished. Another way is to replace the use of exec with system. I used exec() in my Logstash configuration, and it ended the process, so as mentioned above by ChrisCorea, it is better to use another approach.
3

Another way to do the same thing would be,

system 'python script.py', params1, params2

3 Comments

system 'python script.py', *[params1, params2]
You're not catching the result. And system 'python', *["script.py", params1, params2] is more accurate, I think.
Yes I know that, and I dont think it is even possible to catch the result through system function. :)
1

I used the following python call from a ruby module.

In my case using exec() didn't work because it interrupts the current process and caused the simulation I was running to fail.

# run python script
`python #{py_path_py} #{html_path_py} #{write_path_py}`

Comments

0

You can use backticks to accomplish this in two ways

result = `python script.py params`

or

result = %(python script.py params)

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.