本文介绍了将带星号的多个文件传递给 Windows 中的 python shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Google 的 Python 练习,我需要能够从命令行执行此操作:

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

其中 python 是 Python shell,babynames.py 是 Python 程序,--summaryfile 是要被我的解释器解释的参数babynames 程序,baby*.html 是匹配该表达式的文件列表.但是,它不起作用,我不确定问题是 Windows 命令外壳还是 Python.baby*.html 表达式没有扩展到完整的文件列表,而是严格作为字符串传递.可以通过这种方式将多个文件传递给一个 Python 程序吗?

Where python is the Python shell, babynames.py is the Python program, --summaryfile is an argument to be interpreted by my babynames program, and baby*.html is the list of files matching that expression. However, it doesn't work and I'm not sure if the problem is the Windows command shell or Python. The baby*.html expression is not being expanded out to the full list of files, instead it's being passed strictly as a string. Can multiple files be passed to a Python program in such a way?

推荐答案

在将通配符传递给执行的程序或脚本之前,Windows 的命令解释器不会像 UNIX shell 那样扩展通配符.

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

结果:

['*.txt']

解决方案:使用 glob 模块.

Solution: Use the glob module.

from glob import glob
from sys import argv

for filename in glob(argv[1]):
    print filename

这篇关于将带星号的多个文件传递给 Windows 中的 python shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 05:59