如何在Ruby中为终端转义字符串? [英] How to escape strings for terminal in Ruby?

查看:93
本文介绍了如何在Ruby中为终端转义字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试启动mplayer。我的文件名包含空格,应将其转义。
这是我正在使用的代码:

I am attempting to start mplayer. My filename contains spaces and these should be escaped. This is the code I am using:

@player_pid = fork do
   exec "/usr/bin/mplayer #{song.file}"
end

其中#{song.file} 包含类似 / home / example / music / 01-song.mp3 的路径。我如何才能正确地转义此变量(以及标题可能包含的其他可能奇怪的字符),以便终端接受我的命令?

where #{song.file} contains a path like "/home/example/music/01 - a song.mp3". How can I escape this variable properly (and possible other weird characters that the title may contain) so the terminal will accept my command?

推荐答案

Shellwords 应该适合您:)

exec "/usr/bin/mplayer %s" % Shellwords.escape(song.file)






在ruby 1.9.x中,看来您必须要求首先

require "shellwords"

但是在ruby 2.0.x中,我不必明确要求它。

But in ruby 2.0.x, I didn't have to explicitly require it.

这篇关于如何在Ruby中为终端转义字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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