使用带有参数的 argparse 模块作为函数

Use argparse module with argument for a function

我正在尝试执行我的功能 play()

import argparse
from num2words import num2words

def play():
    parser = argparse.ArgumentParser()
    parser.add_argument("--b", default=100,type=int,help="b")
    args = parser.parse_args() 
    for file in reversed(range(file)):
        print(num2words(iteration) + " there are")
        print(num2words(iteration) + " there are")

我在 python 命令行中保留 运行:

>>> import myfile
>>> file.play()

但它一直在使用 default=100,例如我如何指定参数 --b 10

将您的程序更改为:

import argparse
from num2words import num2words

def play():
    parser = argparse.ArgumentParser()
    parser.add_argument("--b", default=100,type=int,help="b")
    args = parser.parse_args() 
    for file in reversed(range(file)):
        print(num2words(iteration) + " there are")
        print(num2words(iteration) + " there are")

if __name__ == '__main__':
    play()

并添加您的问题中未显示的所有缺失代码。

在命令行上:

python my_file_name.py --b 10

命令行不是交互式 Python 解释器,即 >>> 提示符。输入 exit() 然后输入这一行。命令行是 Linux/Mac OS X 例如 bash shell; Windows "DOS box".

对于交互式工作,请尝试:

 >>> import sys
 >>> sys.argv.extend(['--b', '10'])
 >>> import myfile
 >>> file.play()