简体   繁体   中英

Windows cmd versus bash for sys.argv - Python

I was trying to run a python script in visual studio 2015 and I wanted to specify a path to my arparse function, however kept receiving an OSError. See Update the problem appears to be a difference in how argparse receives values from command instead of bash behaviour.

Whether I specify it like this

C:\Users\Sayth\Documents\Racing\XML\*xml

or like this

C:\\Users\\Sayth\Documents\\Racing\\XML\\*xml

I get an OSError that the path is not found

OSError: Error reading file 'C:\\Users\\Sayth\\Documents\\Racing\\XML\\*xml': failed to load external entity "file:/C://Users//Sayth/Documents//Racing//XML//*xml"

Update I copied the script and XML file to a test directory. From here I have run the script on 2 different shells on windows.

On command cmd

C:\Users\Sayth\Projects
λ python RaceHorse.py XML\*xml
Traceback (most recent call last):
  File "RaceHorse.py", line 42, in <module>
    tree = lxml.etree.parse(file)
  File "lxml.etree.pyx", line 3427, in lxml.etree.parse (src\lxml\lxml.etree.c:79720)
  File "parser.pxi", line 1782, in lxml.etree._parseDocument (src\lxml\lxml.etree.c:115914)
  File "parser.pxi", line 1808, in lxml.etree._parseDocumentFromURL (src\lxml\lxml.etree.c:116264)
  File "parser.pxi", line 1712, in lxml.etree._parseDocFromFile (src\lxml\lxml.etree.c:115152)
  File "parser.pxi", line 1115, in lxml.etree._BaseParser._parseDocFromFile (src\lxml\lxml.etree.c:109849)
  File "parser.pxi", line 573, in lxml.etree._ParserContext._handleParseResultDoc (src\lxml\lxml.etree.c:103323)
  File "parser.pxi", line 683, in lxml.etree._handleParseResult (src\lxml\lxml.etree.c:104977)
  File "parser.pxi", line 611, in lxml.etree._raiseParseError (src\lxml\lxml.etree.c:103843)
OSError: Error reading file 'XML\*xml': failed to load external entity "XML/*xml"

When I change it to git bash It reads the file I get an error however it shows its working.

Sayth@renshaw-laptop ~/Projects
λ python RaceHorse.py XML/*xml
Traceback (most recent call last):
  File "RaceHorse.py", line 50, in <module>
    nomination_table.append([race_id] + [nomination.attrib[name] for name in horseattrs])
  File "RaceHorse.py", line 50, in <listcomp>
    nomination_table.append([race_id] + [nomination.attrib[name] for name in horseattrs])
  File "lxml.etree.pyx", line 2452, in lxml.etree._Attrib.__getitem__ (src\lxml\lxml.etree.c:68544)
KeyError: 'race_id'

I have a simple argparse function

parser = argparse.ArgumentParser(description=None) 


def GetArgs(parser): 
    """Parser function using argparse""" 
    # parser.add_argument('directory', help='directory use',
    #                     action='store', nargs='*')

    parser.add_argument("files", nargs="+") 
    return parser.parse_args() 


fileList = GetArgs(parser) 

Update 2 Based on comments am trying to implement glob to enable use of windows shells. glob is returning an error that its object the parser has no object len.

updated glob parser

def GetArgs(parser): 
    """Parser function using argparse""" 
    # parser.add_argument('directory', help='directory use',
    #                     action='store', nargs='*')

    parser.add_argument("files", nargs="+") 
    files = glob.glob(parser.parse_args())
    return files


filelist = GetArgs(parser)

Returns this error.

TypeError was unhandled by user code
Message: object of type 'Namespace' has no len()

The following should work with both the Windows cmd shell and bash because it will glob any filenames it receives (which can happen if the shell didn't do it already):

import argparse
from glob import glob

parser = argparse.ArgumentParser(description=None)

def GetArgs(parser):
    """Parser function using argparse"""

    parser.add_argument("files", nargs="+")
    namespace = parser.parse_args()
    files = [filename for filespec in namespace.files for filename in glob(filespec)]
    return files

filelist = GetArgs(parser)

However, I don't think having GetArgs() add arguments to the parser it was passed is a good design choice (because it could be an undesirable side-effect if the parser object is reused).

even very short and simple I still consider it worth the answer not only comment because python is multi platform and for that reason when you work with path you should prefer using

from os import path

to avoid problems running your app on different platforms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM