2015-12-01 20 views
-1

我想執行我的功能play()使用帶有參數argparse模塊功能

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

+0

看起來像你從交互式解釋(REPL),而不是shell(命令行) – wim

+0

如何從外殼打來的? – Jshee

+1

你可以覆蓋'sys.argv'的值,argparse會接受它。 –

回答

1

程序更改爲:

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框」。

對於交互工作的嘗試:

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

什麼是文件?什麼是迭代? – wim

+0

如果我在命令行中執行此操作,我會得到:python file.py --b 10 ^ SyntaxError:無效的語法 – Jshee

+0

無論OP在程序中有什麼但未在問題的代碼中顯示。 –