【问题标题】:How to deal with paths with spaces on Linux when coding in Python 2.7?在 Python 2.7 中编码时如何在 Linux 上处理带空格的路径?
【发布时间】:2016-04-26 14:46:03
【问题描述】:

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

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/”的终端中的此代码并使用 root 帐户测试了此处给出的答案:

./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 作为答案,因为他帮助我找到了问题的根源。

【问题讨论】:

    标签: linux python-2.7


    【解决方案1】:

    另外,考虑替换字符串中所有不允许出现在文件名中的特殊字符,如 '&'、''、'|'、'*'、'?' 等。逃跑了

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这是问题的直接答案,代码示例有效。
      【解决方案3】:

      使用\跳过空格

      例如:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-01
        • 2013-09-10
        • 1970-01-01
        • 2016-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多