16

I'm trying to create a program that scans a text file and passes arguments to subprocess. Everything works fine until I get directories with spaces in the path.

My split method, which breaks down the arguments trips up over the spaces:

s = "svn move folder/hello\ world anotherfolder/hello\ world" task = s.split(" ") process = subprocess.check_call(task, shell = False) 

Do, either I need function to parse the correct arguments, or I pass the whole string to the subprocess without breaking it down first.

I'm a little lost though.

3
  • Can you rely on a fixed number of space-delimited left tokens? Commented Aug 7, 2012 at 12:42
  • 1
    how about quoting file names? Commented Aug 7, 2012 at 12:45
  • 1
    if you create the filename that is being read, why not have the values comma seperated? and then split on "," instead of all the hassle? Commented Aug 7, 2012 at 12:47

2 Answers 2

24

Use a list instead:

task = ["svn", "move", "folder/hello world", "anotherfolder/hello world"] subprocess.check_call(task) 

If your file contains whole commands, not just paths then you could try shlex.split():

task = shlex.split(s) subprocess.check_call(task) 
Sign up to request clarification or add additional context in comments.

1 Comment

thank you thank you! using a list solves all sorts of weird quoting/escaping issues +1
0

This helped me very much trying to get very complex file specs, from a catalog of music in an irregular folder structure, into ffplay. I never did get it to work with a string variable in os.system() call nor in subprocess.call(). It only worked putting the string directly into the call.

subprocess.call( "ffplay", "-nodisp", "-autoexit", 'complex path string' )

I finally found the list method suggested by jfs (THANK YOU!). It enables using a variable for the filespec. The key was to put the variable into a list without any quotes embedded in the string. The list furnishes the required quotes and works GREAT! Here is the "list" solution:

songspec = "a complex /media/mint filespec without embedded quotes!" playsong = ["ffplay", "-nodisp", "-autoexit", songspec] subprocess.call(playsong) 

This works PERFECTLY and I can automatically step through my list of songs with no problem. It took me about 3 hours to get this one operation functioning.

1 Comment

Please don't add "thank you" as an answer. Instead, vote up the answers that you find helpful. - From Review

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.