Passing multiple files with asterisk to python shell in Windows

前端 未结 4 2070
忘了有多久
忘了有多久 2020-12-31 05:08

I\'m going through Google\'s Python exercises and I need to be able to do this from the command line:

python babynames.py --summaryfile baby*.html

相关标签:
4条回答
  • 2020-12-31 05:34

    Using argparse:

    import argparse
    parser=argparse.ArgumentParser()
    parser.add_argument(dest='wildcard',nargs='+')
    
    print(parser.parse_args().wildcard)
    
    0 讨论(0)
  • 2020-12-31 05:35

    Cross-platform:

    import glob
    if '*' in sys.argv[-1]:
         sys.argv[-1:] = glob.glob(sys.argv[-1])
    continue...
    
    0 讨论(0)
  • 2020-12-31 05:43

    Windows' command interpreter does not expand wildcards as UNIX shells do before passing them to the executed program or script.

    python.exe -c "import sys; print sys.argv[1:]" *.txt
    

    Result:

    ['*.txt']
    

    Solution: Use the glob module.

    from glob import glob
    from sys import argv
    
    for filename in glob(argv[1]):
        print filename
    
    0 讨论(0)
  • 2020-12-31 05:46

    You can do it from UNIX-like shells, right in the from you wrote. In my case, Git Bash did the job - it accepts asterisks as input and process them correctly.

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