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

标签 linux python-2.7

我有一个 Python 脚本可以处理 Linux Mint 上目录中的文件。部分代码如下:

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) 时会抛出这个错误:

/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)

编辑:我找到了错误的来源:我正在使用的库的 Makefile(从 Internet 某处下载)不支持路径中的空格。

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

./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。

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

最佳答案

您应该能够用转义版本替换空格。 尝试:

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

关于linux - 在 Python 2.7 中编码时如何处理 Linux 上带空格的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34905403/

相关文章:

linux - 如何使用期望脚本登录远程计算机时跳过横幅?

c++ - '移植' conio.h 编写的代码到 curses.h

linux - Uinput 和树莓派

python - 如何避免使用 python 覆盖 excel 中的单元格?

Python json获取具体故事和图片

c++ - 远程端点 : Transport endpoint is not connected

c++ - "read_format"结构的 "perf_event_attr"属性的选项到底是什么?

python - 使用python的带有字典的配置文件

python - 有一个函数在打印时转换成它的名字

python lxml 获取节点的名称