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,667
  • 4
  • 34
  • 56
eterey
  • 390
  • 1
  • 4
  • 16
  • 4
    dup of http://stackoverflow.com/questions/2232/calling-bash-commands-from-ruby ? – cmd Sep 05 '13 at 20:35

5 Answers5

30

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

result = `python script.py params`
maniacalrobot
  • 2,413
  • 2
  • 18
  • 20
11

One way would be exec.

result = exec("python script.py params")
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • 5
    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. – Agent 0 Aug 12 '19 at 15:34
3

Another way to do the same thing would be,

system 'python script.py', params1, params2
Sandeep
  • 20,908
  • 7
  • 66
  • 106
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
  • 19,677
  • 20
  • 102
  • 125