简体   繁体   中英

Running command line commands from Thor executable

In my executable Ruby file I have the following:

#!/usr/bin/env ruby

require 'thor'

include Thor::Actions

class UI < Thor
  # def self.source_root
  #   File.dirname(__FILE__)
  # end

  desc "makecal", "Generates postscript calendar to your desktop"
  def makecal
    # puts `ls ~`
    puts run('ls ~')
    # puts run "pcalmakecal -B -b all -d Helvetica/8 -t Helvetica/16 -S #{Time.now.month} #{Time.now.year} > ~/Desktop/#{Time.now.month}-#{Time.now.year}"
  end
end

UI.start

In the terminal when I run the file as is I get an empty line as Thor's run command is returning a NilClass.

However, when I un-comment the puts `ls ~` and comment out Thor's run method I get an output of my home directory as expected.

I'm having trouble figuring out why I can't get Thor's run method to work like Ruby's ticks.

Any ideas where I may have went wrong?

Thanks for looking

I didn't put the include statement inside my class and that messed things up. The code should be:

#!/usr/bin/env ruby

require 'makecal'


class UI < Thor
  include Thor::Actions
  # def self.source_root
  #   File.dirname(__FILE__)
  # end
  #

  desc "makecal", "Generates postscript calendar to your desktop"
  def makecal
    # puts `ls ~`
    puts run('ls ~')
    # puts run "pcal -B -b all -d Helvetica/8 -t Helvetica/16 -S #{Time.now.month} #{Time.now.year} > ~/Desktop/#{Time.now.month}-#{Time.now.year}"
  end
end

UI.start

Thor's documentation on this method is actually wrong and incomplete. It documents that it returns the "contents of the command" (which I assume means the standard output), but it, by defualt, does nothing.

But , you can, apparently, use the :capture option to get what you want:

unless options[:pretend]
  config[:capture] ? `#{command}` : system("#{command}")
end

So, try doing

puts run("ls ~", :capture => true)

And see if that does it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM