Parsing Command line arguments in python which has spaces

旧时模样 提交于 2019-11-30 15:06:04

问题


I am invoking the script from ant . I am getting it as a single string from the caller but python is strangely treating it as two individual strings.I have script that reads a file name with it's path in windows. The folder structure may or may not have spaces in between

Here is an example

test.py D:/test/File Name

I know this can be done using optparse. Is there any way that i can read the param as single argument like i want to get it in sys.argv[index] (as a single string). I have tired prefixing with ' and " but with no success.


回答1:


You pass the folder name wrapped in quotes:

test.py "D:\test\File Name"

sys.argv[1] will contain the folder path, spaces included.

If for some reason you cannot quote the folder name, you will need to use the ctypes module and use the Win32 API's GetCommandLine function. Here's a functional example.




回答2:


The convention for passing spaces as arguments is by escaping spaces.

test.py D:/test/File\ Name

This way you'll have access to "D:/test/File Name" in your python script.




回答3:


According to MS: https://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx

Backslashes are interpreted literally, unless they immediately precede a double quotation mark.

I'm wondwring if Python on Windows uses this method: https://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx

To parse the command line to create sys.argv. In theory it should do it.



来源:https://stackoverflow.com/questions/20784997/parsing-command-line-arguments-in-python-which-has-spaces

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