2

I have a subprocess in Python, which runs a Ruby script.

import subprocess
cmd="ruby -v"
p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, env={ 'PATH': '/sbin:/bin:/usr/bin' })
p.wait()
output, errors = p.communicate()
status = 'Estado de la app: ' + str(output) + 'Errores: ' + str(errors)
return status

The problem is that it gives a wrong Ruby version. This runs on a server so through SSH I installed Ruby 2.2.1 with rvm, and when I run ruby -v it gives me the right information. But when I run the python from web2py it gives me an older version of Ruby, which is the one in /usr/bin/ruby.

It is like the subprocess runs in a whole different shell. What could it be?

Thanks

facumedica
  • 658
  • 1
  • 7
  • 20
  • SSH into the box and run `which ruby`. Try the same from within your script. Try using the full path name to invoke the Ruby interpreter you want to use in the script. – chucksmash Sep 07 '15 at 17:45
  • unrelated: drop `p.wait()` call. It may deadlock your program and it is completely unnecessary here, see [What difference between subprocess.call() and subprocess.Popen() makes PIPE less secure for the former?](http://stackoverflow.com/q/32364849/4279) – jfs Sep 07 '15 at 19:51

2 Answers2

3

rvm works by injecting hooks into your shell. This is typically done in your .bash_profile (see here).

Bash is probably your default shell, but regardless, your .bash_profile is only read by your shell if it's a login shell, which a shell spawned by subprocess.Popen isn't. In other words, rvm isn't loaded at all when you use subprocess.Popen

To fix your issue, you should explicitly invoke rvm:

rvm 2.2.1 do ruby ...

(e.g. in your case rvm 2.2.1 do ruby -v)

This is documented in the rvm scripting documentation.

Community
  • 1
  • 1
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
0

I did this:

/usr/local/rvm/wrappers/ruby-2.2.1/ruby /scripts/myscript.rb

Which means I execute the ruby from the folder of rvm. Thanks for your help!

facumedica
  • 658
  • 1
  • 7
  • 20