Broken_Window
Broken_Window

Reputation: 2093

How to deal with paths with spaces on Linux when coding in Python 2.7?

I have a python script that process files in a directory on Linux Mint. Part of the code is like the following:

path_to_dir = "/home/user/Im a folder with libs to install/"

if os.path.isdir(path_to_dir):
    print "it can locate the directory"
    os.chdir(path_to_dir) # everything ok here :D
    subprocess.call(['./configure'], shell = True)
    subprocess.call(['make'], shell = True)
    subprocess.call(['make install'], shell = True) # problem happens here

When executing subprocess.call(['make install'], shell = True) it throws this error:

/bin/bash: /home/user/Im: No such file or directory
make[3]: *** [install-libLTLIBRARIES] Error 127
make[2]: *** [install-am] Error 2
make[1]: *** [install-recursive] Error 1
make: *** [install-recursive] Error 1

How can I deal with spaces in paths when executing subprocess.call(['make install'], shell = True)? (I'm using Python 2.7)

Edit: I found out the source of the errors: the Makefile of the libraries I'm using (downloaded from somewhere on Internet) don't support spaces in the path.

I tested the answer given here using this code in the terminal located in the path "/home/user/Im a folder with libs to install/" and using a root account:

./configure
make
make install /home/user/Im\ a\ folder\ with\ libs\ to\ install/Makefile

It gives me the same error:

/bin/bash: /home/user/Im: No such file or directory
[install-libLTLIBRARIES] Error 127
make[3]: se sale del directorio «/home/user/Im a folder with libs to install/»
make[2]: *** [install-am] Error 2
make[2]: se sale del directorio «/home/user/Im a folder with libs to install/»
make[1]: *** [install-recursive] Error 1
make[1]: se sale del directorio «/home/user/Im a folder with libs to install/»
make: *** [install-recursive] Error 1

It can locate the folder, but it seems that, internally, it passes the path to Linux bash with no scape characters.

I'm accepting nafas as the answer because he helped me to locate the source of the problem.

Upvotes: 4

Views: 9017

Answers (3)

Anand Guddu
Anand Guddu

Reputation: 51

Also, think about replacing all special characters like '&', '<', '>', '|', '*', '?', etc. in the string which are not permitted in filename and must be escaped

path_to_dir = path_to_dir.replace(" ", "\\ ").replace("?", "\\?").replace("&", "\\&").replace("(", "\\(").replace(")", "\\)").replace("*", "\\*").replace("<", "\\<").replace(">", "\\>")

Upvotes: 3

Stephen Lane-Walsh
Stephen Lane-Walsh

Reputation: 86

You should be able to replace spaces with their escaped versions. Try:

path_to_dir = path_to_dir.replace(" ", "\\ ")

Upvotes: 7

nafas
nafas

Reputation: 5423

skip the spaces using \

e.g. :

Im\ a\ folder\ with\ libs\ to\ install

Upvotes: 2

Related Questions