Windows commands in ruby - ruby-on-rails

How do I run a Windows command in an Ruby app?
I am trying to run something like:
output = `cd #{RAILS_ROOT}/lib && java HelloWorld #{param1} #{param2}`
I print the result of the line above and paste it to a command prompt in Windows and it works just fine. However, when i run app and hit this code, output is blank rather than have a string I get back from HellowWorld. In HelloWorld I do a System.out.print("helloworld")
The following:
output = `cmd.exe /C dir`
puts "OUTPUT #{output}"
Returns:
OUTPUT

Issue in JRuby 1.5.3 fixed in JRuby 1.5.5:
http://www.jruby.org/2010/11/10/jruby-1-5-5.html

Try to use File#join here. It will generate crossplatform path for you
http://apidock.com/ruby/File/join/class
my_path = File.join(RAILS_ROOT, "lib")
output = `cd #{my_path} && java HelloWorld #{param1} #{param2}`
Also you can execute your system commands this way:
`cd #{my_path} && java HelloWorld #{param1} #{param2}`
system("cd #{my_path} && java HelloWorld #{param1} #{param2}")
%x[cd #{my_path} && java HelloWorld #{param1} #{param2}]
Related topic: System call from Ruby

Backticks work fine for me. Try:
output = `dir`
to prove to yourself that it's working. At that point, your question is how to run a Java app from the command line, or why your particular app isn't work. Note that you can temporarily change the working directory like this:
Dir.chdir(File.join(RAILS_ROOT,'lib')) do
output = `...`
end

Related

xonsh "which" equivalent - how to test if a (subprocess mode) command is available?

I would like to test (from xonsh) if a command is available or not. If I try this from the xonsh command prompt:
which bash
Then it works:
user#server ~ $ which bash
/usr/bin/bash
But it does not work from xonsh script:
#!/usr/bin/env xonsh
$RAISE_SUBPROC_ERROR = True
try:
which bash
print("bash is available")
except:
print("bash is not available")
Because it results in this error:
NameError: name 'which' is not defined
I understand that which is a shell builtin. E.g. it is not an executable file. But it is available at the xnosh command prompt. Then why it is not available inside an xonsh script? The ultimate question is this: how can I test (from an xonsh script) if a (subprocess mode) command is available or not?
import shutil
print(shutil.which('bash'))
While nagylzs' answer led me to the right solution, I found it inadequate.
shutil.which defaults to os.environ['PATH']. On my machine, the default os.environ['PATH'] doesn't contain the active PATH recognized by xonsh.
~ $ os.environ['PATH']
'/usr/bin:/bin:/usr/sbin:/sbin'
I found I needed to pass $PATH to reliably resolve 'which' in the xonsh environment.
~ $ $PATH[:2]
['/opt/google-cloud-sdk/bin', '/Users/jaraco/.local/bin']
~ $ import shutil
~ $ shutil.which('brew', path=os.pathsep.join($PATH))
'/opt/homebrew/bin/brew'
The latest version of xonsh includes a built-in which command. Unfortunately, the version included will emit an error on stdout if the target isn't found, a behavior that is not great for non-interactive use.
As mentioned in another answer, which exists in the current version of xonsh (0.13.4 as of 15/12/2022) so your script would work. However, it outputs its own error message so it's necessary to redirect stderr to get rid of it.
Also, unless you redirect its stdout as well (using all>), it migh be a good idea to capture its output so the final version would look like this:
#!/usr/bin/env xonsh
$RAISE_SUBPROC_ERROR = True
try:
bash = $(which bash err> /dev/null)
print(f"bash is available: {bash}")
except:
print("bash is not available")

Run script Ruby on Rails

I have a set of commands that I run in the bin/rails console, for example:
AppConfig.settings.captcha.enable = false
success = user.sign_up
etc ...
Can I make a script like bin/bash to execute all commands at once? (I would like it to be a executable file, since I want to change the input data in it)
You can put the commands into a file (script), add the shebang line (#!/usr/bin/env ruby), make the file executable and run it from the command line like so:
#!/usr/bin/env ruby
# require ... (load the libraries here)
...
AppConfig.settings.captcha.enable = false
success = user.sign_up
#etc ...
# Make executable
chmod u+x my_script.rb
# Run the script
/path/to/my_script.rb

Calling Bash Commands From Ruby with russian symbols return 1

Calling bash command
cmd = '/usr/bin/mediainfo "/var/avalon/dropbox/Лекции_для_молодых_ученых/Nabiullin_SciERes_1.flv" --Output=XML'
out = `#{cmd}`
In rails project 'avalom media system' return error code 1.
Removal of russian letters out of the path cmd = '/usr/bin/mediainfo "/var/avalon/dropbox/Nabiullin_SciERes_1.flv" --Output=XML' , a call to another command
cmd = 'head "/var/avalon/dropbox/Лекции_для_молодых_ученых/Nabiullin_SciERes_1.flv"'
or run the command in irb or project environment or bash
- everything is fine.
Thx.
Error when i try add media file to collection with russian letters in file:543 => in gem media info file:473
Console encoding - utf-8. Command string encoding - utf-8.
The cause of this problem is that ENV["LANG"] of avalon is C.
Set ENV["LANG"] to en_US.utf-8 resolve this trouble.

check syntax of ruby/jruby script using jruby -c syntax check (inside ruby code)

I am in a search of some way , using which in ruby code I should be able to create a temp file and then append some ruby code in that, then pass that temp file path to jruby -c to check for any syntax errors.
Currently I am trying the following approach:
script_file = File.new("#{Rails.root}/test.rb", "w+")
script_file.print(content)
script_file.close
command = "#{RUBY_PATH} -c #{Rails.root}/test.rb"
eval(command);
new_script_file.close
When I inspect command var, it is properly showing jruby -c {ruby file path}. But when I execute the above piece of code I am getting the following error:
Completed 500 Internal Server Error in 41ms
SyntaxError ((eval):1: dhunknown regexp options - dh):
Let me know if any one has any idea on this.
Thanks,
Dean
eval evaluates the string as Ruby code, not as a command line invocation:
Since your command is not valid Ruby syntax, you get this exception.
If you want to launch a command in Ruby, you can use %x{} or ``:
output1 = ls
output2 = %x{ls}
Both forms will return the output of the launched command as a String, if you want to process it. If you want this output to be directly displayed in the user terminal, you can use system():
system("ls")

how to use execute() in groovy to run any command

I usually build my project using these two commands from command line (dos)
G:\> cd c:
C:\> cd c:\my\directory\where\ant\exists
C:\my\directory\where\ant\exists> ant -Mysystem
...
.....
build successful
What If I want to do the above from groovy instead? groovy has execute() method but following does not work for me:
def cd_command = "cd c:"
def proc = cd_command.execute()
proc.waitFor()
it gives error:
Caught: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The
system cannot find the file specified
at ant_groovy.run(ant_groovy.groovy:2)
Or more explicitly, I think binil's solution should read
"your command".execute(null, new File("/the/dir/which/you/want/to/run/it/from"))
According to this thread (the 2nd part), "cd c:".execute() tries to run a program called cd which is not a program but a built-in shell command.
The workaround would be to change directory as below (not tested):
System.setProperty("user.dir", "c:")
"your command".execute(null, /the/dir/which/you/want/to/run/it/from)
should do what you wanted.
Thanks Noel and Binil, I had a similar problem with a build Maven.
projects = ["alpha", "beta", "gamma"]
projects.each{ project ->
println "*********************************************"
println "now compiling project " + project
println "cmd /c mvn compile".execute(null, new File(project)).text
}
I got to fix the issue by running a command as below:
i wanted to run git commands from git folder, so below is the code which worked for me.
println(["git","add","."].execute(null, new File("/Users/xyz/test-org/groovy-scripts/$GIT_REPOS/")).text)
println(["git","commit","-m","updated values.yaml"].execute(null, new File("/Users/xyz/test-org/groovy-scripts/$GIT_REPOS/")).text)
println(["git","push","--set-upstream","origin","master"].execute(null, new File("/Users/xyz/test-org/groovy-scripts/$GIT_REPOS/")).text)

Resources