在 Python 2.7 中编码时如何处理 Linux 上带有空格的路径?

问题描述:

我有一个 Python 脚本,用于处理 Linux Mint 目录中的文件.部分代码如下:

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

当执行 subprocess.call(['make install'], shell = True) 时,它会抛出这个错误:

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

在执行subprocess.call(['make install'], shell = True) 时如何处理路径中的空格?(我使用的是 Python 2.7)

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

我发现了错误的来源:我正在使用的库的 Makefile(从 Internet 某处下载)不支持路径中的空格.

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.

我在位于路径/home/user/Im a folder with libs to install/"中的终端中使用此代码并使用root帐户测试了此处给出的答案:

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

它给了我同样的错误:

/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

它可以定位文件夹,但它似乎在内部将路径传递给 Linux bash,而没有转义字符.

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

我接受 nafas 作为答案,因为他帮助我找到了问题的根源.

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

使用 \

例如:

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