Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 928
Broken_Window Avatar asked Oct 24 '25 06:10

Broken_Window


2 Answers

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

path_to_dir = path_to_dir.replace(" ", "\\ ")
like image 97
Stephen Lane-Walsh Avatar answered Oct 26 '25 22:10

Stephen Lane-Walsh


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(">", "\\>")
like image 40
Anand Guddu Avatar answered Oct 26 '25 22:10

Anand Guddu