Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling directories with spaces Python subprocess.call()

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.

like image 750
james_dean Avatar asked Aug 07 '12 12:08

james_dean


People also ask

What does subprocess call () Python do?

The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.

What is difference between subprocess Popen and call?

Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

What is CWD in subprocess?

subprocess. Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ( 'd:\\test\\local' ), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab .

What does subprocess Check_call return?

exception subprocess. CalledProcessError. Subclass of SubprocessError , raised when a process run by check_call() , check_output() , or run() (with check=True ) returns a non-zero exit status.


1 Answers

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)
like image 68
jfs Avatar answered Oct 07 '22 16:10

jfs