Command Line Arguments in Python

Raven
隨筆趣事
Published in
Aug 28, 2021

The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments.

意思就是我們使用cmd,來執行程式命令時,跟隨在後面的參數,就叫做Command Line Arguments:

command line arguments

Python 提供了多種方法來處理這些類型的參數。 最常見的三種是:

  • Using sys.argv
  • Using getopt module
  • Using argparse module

Using sys.argv

使用方法也很簡單,一開始先import sys,就可以使用了。

sys.py
cmd line

Using getopt module

Python 的 getopt module其實跟 c 的 getopt()很類似。

與 sys module 不同的是,getopt 通過參數驗證擴展了輸入字符串的分離。 它允許短選項和長選項,包括賦值。

demoe2.py
cmd

Using argparse module

最後一個,也是我最常用的! 它比前面兩個有更多功能,且更好理解。

Example 1:

example1
cmd

Example 2:

example2
cmd

Example 3(實戰演練):

example3
等於可以省略喔~

--

--

Raven
隨筆趣事

熱愛寫code,平時遇到有趣的事情,也會上來寫寫,抒發自己的心情。