在Python中,有一些框架可以幫助處理命令行參數(shù),其中一個很常用的是 argparse 模塊。它可以幫助你定義命令行參數(shù)并解析它們。下面是一個簡單的示例,演示了如何使用 argparse 來處理命令行參數(shù):
import argparse
def main():
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f', '--file', help='Input file path')
parser.add_argument('-o', '--output', help='Output file path')
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose mode')
args = parser.parse_args()
if args.verbose:
print("Verbose mode activated.")
if args.file:
print("Input file:", args.file)
if args.output:
print("Output file:", args.output)
if __name__ == "__main__":
main()
這個腳本允許你指定輸入文件、輸出文件以及是否啟用詳細(xì)模式。你可以像這樣在命令行中運行它:
python script.py -f input.txt -o output.txt -v
這與使用 Linux 的 getopt 或者 uniopt 非常相似,因為它們都提供了一個簡單的方法來解析命令行參數(shù),并且支持選項的簡寫形式(比如 -f 或者 -o)。