2

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)

I can use the program like this:

./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

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 \)

wong2
  • 34,358
  • 48
  • 134
  • 179
  • as a side note, I've been thinking about putting some of my lossless files on my ipod, from what I understand this is an acceptable format. thanks for asking this question. It may come in handy. – matchew May 15 '11 at 15:53

3 Answers3

6

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"])
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1

What you are literally asking is impossible because what is typed on the command line is lost when the shell does the parsing. The shell parses the special characters and passes the result to python. By the time python gets the string all the special characters have been processed and thrown away. That is, this is not the fault of bash but the design of bash (and most other shells).

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
0

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

The '\' in above command is used to escape ' ', '(' and ')', that's, it equals to

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

You python program can never see the '\' in its argv[1].

If you really need a '\' before each ' ', '(' and ')', you can add it in your python program easily.

Huang F. Lei
  • 1,835
  • 15
  • 23