Created
March 5, 2014 15:22
-
-
Save jhjguxin/9369328 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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