python - 从 sys.argv 中删除已解析的选项及其值

标签 python file-io python-2.5 optparse

我正在尝试使用 optparse(将命令行选项解析到我的脚本)和 fileinput(以灵活地通过管道或文件提供数据输入)。

import optparse, fileinput

parser = OptionParser()    
parser.add_option("-v", action="store_true", dest="verbose")
(options, args) = parser.parse_args()

for line in fileinput.input:
     process(line)

但是 fileinput 尝试使用“-v”选项和文件名,导致“没有这样的文件或目录错误”。因此,要么我需要制作文件输入参数,要么从 sys.argv 中删除已解析的选项,但我不知道如何优雅地执行此操作。有什么指点吗?

最佳答案

来自documentation :

To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed.

因此,您只需传入从 optparse 获得的剩余 args

关于python - 从 sys.argv 中删除已解析的选项及其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9756396/

相关文章:

python - 如何更改元素的文本

python - 如何在 cv2.VideoWriter 中使用 FPS 参数?

python - Python中使用#作为注释的由来?

c - 从文件中选择 float

c++ - 读写缓冲区问题

java - UTF-16格式的文件打不开,UTF-8格式的文件可以

python - 如何在 Jupyter 笔记本中使用来自外部 Python 文件的代码?

python - 使用django在 celery 中传递用户对象

python - Pandas 使用 groupby 迭代数组