Using subprocess.Popen (shell=True) with windows folders

怎甘沉沦 提交于 2020-07-31 03:10:50

问题


I'm currently looking at Popen to automate the compression & storage of documents.

For the compression part, I thought of the following Python line:

subprocess.Popen("WinRAR.exe a -r c:\\03. Notes\\AllTexts *.txt", shell=True)

I keep having error messages, as the command is not able to deal with a folder name that contains a space (03. Notes). This question was asked before several times, and, I must say that I tried all propositions: raw string, double quotes, triple quotes, ... None of them worked.

As I can't change the folder names, and I have no more ideas to try, could someone advise how could I possibly pass this command line successfully ?


回答1:


In Windows you should use quotes for file or directory names (if you want to use spaces inside). In Python, you should escape quotes with \ symbol (if you are using strings inside " quotes). Like this:

"my name is \"Mark\"!"

Or just:

'my name is "Mark"!'

So this will work as expected:

subprocess.Popen("WinRAR.exe a -r \"c:\\03. Notes\\AllTexts\" *.txt", shell=True)

As well as:

subprocess.Popen('WinRAR.exe a -r "c:\\03. Notes\\AllTexts" *.txt', shell=True)


来源:https://stackoverflow.com/questions/40877625/using-subprocess-popen-shell-true-with-windows-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!