簡體   English   中英

從Thor可執行文件運行命令行命令

[英]Running command line commands from Thor executable

在我的可執行Ruby文件中,我有以下內容:

#!/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

在終端當我運行文件時,我得到一個空行,因為Thor的運行命令返回一個NilClass。

但是,當我取消評論puts`ls~`並注釋掉Thor的run方法時,我得到了我的主目錄的輸出。

我無法弄清楚為什么我不能讓Thor的run方法像Ruby的蜱一樣工作。

我可能出錯的任何想法?

謝謝你的期待

我沒有把include語句放在我的類中,這搞砸了。 代碼應該是:

#!/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關於這種方法的文檔實際上是錯誤的和不完整的。 它記錄它返回“命令的內容”(我假設它意味着標准輸出),但它通過defualt什么都不做。

但是 ,顯然,你可以使用:capture選項來獲得你想要的東西:

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

所以,試試吧

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

看看是否這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM