How to deal with paths with spaces on Linux when c

2019-09-11 15:21发布

问题:

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.

回答1:

skip the spaces using \

e.g. :

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



回答2:

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

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