我有一个 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/