解析命令行参数作为通配符 [英] Parsing command-line arguments as wildcards

查看:176
本文介绍了解析命令行参数作为通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的脚本写入所有给定参数到一个文本文件中,用换行符分开。我想用OptionParser到文件列表传递给它。我想补充一对夫妇使用通配符一样的文件 / DIR / *

我试过这样:

  =选择采用OptionParser.new
opts.on(' - 一','--add FILE)做| S |
  把DEBUG:#{S}之前
  @ options.add = S
  把DEBUG:#{@options.add后}
结束
...
高清process_arguments
  @lines_to_add = Dir.glob @ options.add
结束

把当我添加的文件是这样的:

  ./ script.rb -a /路径/ *

我总是只在目录中的第一个文件。所有调试输出只显示目录的第一个文件,它好像OptionParser做一些魔术间pretations

有谁知道如何来处理呢?


解决方案

您正在使用的操作系统(它很重要)。你没有提到

在Windows上,不管你在命令行中输入被传递给程序而无需修改。所以,如果你键入

  ./ script.rb -a /路径/ *

那么参数程序包含 - 一个/路径/ *

在Unix和其他系统类似的壳,壳做的参数扩展的,在命令行自动扩展通配符。所以,当你键入相同的命令以上时,的的外观来查找 /路径/ * 目录中的文件之前扩大了命令行参数你的程序运行。所以,争论到您的程序可能是 - 一个/路径/文件1/路径/文件2

这是很重要的一点是,该脚本无法找到论据​​是否扩大发生,或者用户是否实际键入所有这些文件名了命令行上。

I wrote a simple script that writes all given arguments to a single text file, separated by newline. I'd like to pass a list of files to it using OptionParser. I would like to add a couple of files using wildcards like /dir/*.

I tried this:

opts = OptionParser.new 
opts.on('-a', '--add FILE') do |s| 
  puts "DEBUG: before #{s}"
  @options.add = s
  puts "DEBUG: after #{@options.add}"
end
...
def process_arguments
  @lines_to_add = Dir.glob @options.add
end

Put when I add files like this:

./script.rb -a /path/*

I always get only the first file in the directory. All the debug outputs show only the first file of directory, and it seems as if OptionParser does some magic interpretations

Does anyone know how to handle this?

解决方案

You didn't mention which operating system you are using (it matters).

On Windows, whatever you type on the command line gets passed to the program without modification. So if you type

./script.rb -a /path/*

then the arguments to the program contain "-a" and "/path/*".

On Unix and other systems with similar shells, the shell does argument expansion that automatically expands wildcards in the command line. So when you type the same command above, the shell looks to find the files in the /path/* directory and expands the command line arguments before your program runs. So the arguments to your program might be "-a", "/path/file1", and "/path/file2".

An important point is that the script cannot find out whether argument expansion happened, or whether the user actually typed all those filenames out on the command line.

这篇关于解析命令行参数作为通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆