18

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.

Steffi Keran Rani J
  • 3,051
  • 3
  • 25
  • 47
uzumaxy
  • 380
  • 1
  • 4
  • 15
  • 4
    dup of http://stackoverflow.com/questions/2232/calling-bash-commands-from-ruby ? – cmd Sep 05 '13 at 20:35

5 Answers5

28

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

result = `python script.py params`
maniacalrobot
  • 2,287
  • 1
  • 17
  • 20
10

One way would be exec.

result = exec("python script.py params")
steenslag
  • 76,334
  • 16
  • 131
  • 165
  • 3
    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). – ChrisCorea Oct 30 '15 at 17:12
  • 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. – Forgotten Ape Aug 12 '19 at 15:34
3

Another way to do the same thing would be,

system 'python script.py', params1, params2
Sandeep
  • 20,199
  • 7
  • 63
  • 104
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}`
MatthewSteen
  • 91
  • 1
  • 8
0

You can use backticks to accomplish this in two ways

result = `python script.py params`

or

result = %(python script.py params)
Prashanth Sams
  • 16,250
  • 19
  • 96
  • 119