Skip to content

Instantly share code, notes, and snippets.

@jhjguxin
Created March 5, 2014 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhjguxin/9369328 to your computer and use it in GitHub Desktop.
Save jhjguxin/9369328 to your computer and use it in GitHub Desktop.
# simple ruby code example for running python script
path_to_script = File.dirname(__FILE__)
puts "It's a ruby script"
puts "Run python script with backticks"
puts "Result is available in caller.ru"
puts `python #{path_to_script}/processing.py UserName 37`
puts "Run python script with IO\#popen"
puts "Result is available in caller.ru"
IO.popen("python #{path_to_script}/processing.py UserName 37") { |f| puts f.gets }
# or
@result = IO.popen("python #{path_to_script}/processing.py UserName 37")
puts @result.gets
There are few ways to run python scripts from ruby code.
Backticks (`)
Backticks (also called “backquotes”) runs the command in a subshell and returns the standard output from that command.
IO#popen
IO#popen is another way to run a command in a subprocess. popen gives you a bit more control in that the subprocess standard input and standard output are both connected to the IO object.
For example were created caller.ru and processing.py placed in same direcory
# called python script
import sys, json
user=sys.argv[1]
score=sys.argv[2]
# processing
# return processing result
print json.dumps({'user':user, 'score':score})
user@pc:~/$ ruby caller.ru
It's a ruby script
Run python script with backticks
Result is available in caller.ru
{"user": "UserName", "result": "37"}
Run python script with IO#popen
Result is available in caller.ru
{"user": "UserName", "result": "37"}
{"user": "UserName", "result": "37"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment