Parsing Command line arguments in python which has spaces

后端 未结 4 1216
借酒劲吻你
借酒劲吻你 2020-12-31 09:18

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

相关标签:
4条回答
  • 2020-12-31 09:35

    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.

    0 讨论(0)
  • 2020-12-31 09:41

    EDIT!! :
    Depending on the encoder of your command line,
    The ascii encoding reference for a space is normally %20
    So instead of using a space use %20
    https://www.w3schools.com/tags/ref_urlencode.ASP

    As below

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

    Be sure to write it as it is

    Please vote in support if this helps you out. It wasn't as correct the first time I wrote it but now I believe that should do.

    0 讨论(0)
  • 2020-12-31 09:42

    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.

    0 讨论(0)
  • 2020-12-31 09:50

    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.

    0 讨论(0)
提交回复
热议问题