python cmd命令 循环传参数_将参数从cmd传递给python脚本
我在
python中編寫腳本并通過輸入以下命令運行cmd:
C:\> python script.py
我的一些腳本包含基于標志調用的單獨算法和方法.
現在我想通過cmd直接傳遞標志,而不是必須進入腳本并在運行之前更改標志,我想要類似于:
C:\> python script.py -algorithm=2
我讀過人們使用sys.argv幾乎是類似的目的,但是閱讀手冊和論壇我無法理解它是如何工作的.
最佳答案 有一些專門解析命令行參數的模塊:
getopt,
optparse和
argparse.不推薦使用optparse,并且getopt不如argparse強大,所以我建議你使用后者,從長遠來看它會更有幫助.
這是一個簡短的例子:
import argparse
# Define the parser
parser = argparse.ArgumentParser(description='Short sample app')
# Declare an argument (`--algo`), telling that the corresponding value should be stored in the `algo` field, and using a default value if the argument isn't given
parser.add_argument('--algo', action="store", dest='algo', default=0)
# Now, parse the command line arguments and store the values in the `args` variable
args = parser.parse_args()
# Individual arguments can be accessed as attributes...
print args.algo
這應該讓你開始.在最糟糕的情況下,有大量的文檔在線提供(例如,this one)…
總結
以上是生活随笔為你收集整理的python cmd命令 循环传参数_将参数从cmd传递给python脚本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DebugOutputString 使用
- 下一篇: pil库修改图片大小_Gvcode库:一