如何在不转义字符串的情况下读取argv值? [英] How to read argv value without escape the string?

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

问题描述

我正在编写一个名为 flac2m4a 的python脚本,该脚本调用 ffmpeg 将.flac文件转换为.m4a文件.核心程序是这样的:

I'm writing a python script called flac2m4a which calls ffmpeg to convert a .flac file to .m4a file. the core program is like this:

cmd = "ffmpeg -i %s -acodec alac %s.m4a" % (sys.argv[1], sys.argv[1][:-5])
os.system(cmd)

我可以这样使用程序:

./flac2m4a path_to_the_song.flac  

但是当我为一些带有特殊字符的歌曲运行它们时:

But when I run it for some songs with special chars in their name:

./flac4m4a.py Justin\ Bieber\ -\ Never\ Say\ Never\ -\ The\ Remixes/01\ -\ Never\ Say\ Never\ \(feat.\ Jaden\ Smith\).flac

在linux下,当我按Tab键自动完成时,特殊字符将以 \ 转义,但是当我从 sys.argv [1] 读取时,它们将通过Python转换为普通字符串:

under linux, when I press tab to autocomplete, the special chars will be escaped with a \, but when I read it from sys.argv[1], they will be converted to the normal string by Python:

Justin Bieber - Never Say Never - The Remixes/01 - Never Say Never (feat. Jaden Smith).flac

所以我只想知道如何完全按照用户输入的内容(使用那些 \ )

So I just want to know how to read the argv[1] exactly as what the user input(with those \)

推荐答案

虽然可以为Shell引用一个字符串,但您不应该首先使用Shell来执行命令,从而避免了任何引用.使用 subprocess.call()代替 os.system():

While it is possible to quote a string for the shell, you should not use the shell to execute your command in the first place, rendering any quoting unnecessary. Use subprocess.call() instead of os.system():

subprocess.call(["ffmpeg", "-i", sys.argv[1], "-acodec", "alac",
                 sys.argv[1][:-5] + ".m4a"])

这篇关于如何在不转义字符串的情况下读取argv值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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