pythonjythonwlst

Parsing Command line arguments in python which has spaces


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.


Solution

  • 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.