如何在 Ruby 中执行 Windows CLI 命令?
我有一个文件位于目录“C:\Documents and Settings\test.exe”中,但是当我在单个 qoutes 中写入命令 `C:\Documents and Settings\test.exe
时(我我无法在此框中显示),用于在 Ruby 中执行命令,但我无法执行此操作,收到的错误是找不到文件或目录。我尝试用“//”和“\”替换“\”,但似乎没有任何效果。我还使用了system、IO.popen和exec命令,但所有努力都是徒劳的。另外 exec 命令使程序退出,这是我不希望发生的。
提前致谢。
I have a file located in the directory "C:\Documents and Settings\test.exe" but when I write the command `C:\Documents and Settings\test.exe
in single qoutes(which I am not able to display in this box), used for executing the commands in Ruby, I am not able to do so and the error that I recieve is No file or Directory found. I have tried replacing "\" with "//" and "\" but nothing seems to work. I have also used system, IO.popen and exec commands but all efforts are in vain. Also exec commands makes the program to make an exit which I don't want to happen.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
反引号环境就像双引号,因此反斜杠用于转义。此外,Ruby 会将空格解释为分隔命令行参数,因此您需要引用整个内容:
另一个选择是使用
system
并强制使用第二个参数。如果system
获取多个参数,它会将第一个参数视为要执行的命令的路径,并且您不需要引用该命令:请注意使用 single 引号,所以我们没有转义反斜杠。
当然,这不会给你带来标准的输出/错误,所以如果你使用的是 Ruby 1.9.2,你可以使用非常方便的
Open3
库,它的工作方式类似于system,但为您提供有关刚刚运行的进程的更多信息:
The backtick environment is like double-quotes, so backslash are used for escaping. Further, Ruby will interpret the spaces as separating command-line arguments, so you need to quote the entire thing:
Another option is to use
system
and force a second argument. Ifsystem
gets more than one argument, it treats the first argument as the path to the command to execute and you don't need to quote the command:Note the use of single quotes, so we don't have escape the backslashes.
Of course, this won't get you the standard out/error, so if you are on Ruby 1.9.2, you can use the awesomely handy
Open3
library, which works likesystem
, but gives you more information about the process you just ran:或
或任何引用中的内容
or
or whatever in qoutes