傳遞命令列參數範例程式碼 (C 和 Python)

來源:互聯網
上載者:User

標籤:rgs   輸入參數   pass   使用   tps   ocs   命令列參數   bsp   資料   

C語言

在 C 語言中, 使用 main 函數的輸入參數 argc 和 argv 傳入命令列參數.

  • argc 為 int 類型, 表示傳入命令列參數的個數 (argument count);
  • argv 為 char** 類型, 表示命令列參數向量 (argument vector), 每個命令列參數為字串類型, 因此 參數 argv 也可以看做是字串數組.

範例程式碼如下:

/** filename: pass_args.c* This code is modified a little according to the Arun‘s answer in https://stackoverflow.com/questions/3898021/regarding-mainint-argc-char-argv*/#include <stdio.h>int main(int argc, char *argv[]){    int i = 0;    printf(" argc = %d\n", argc);    for (; i < argc; ++i) {        printf(" argv[ %d ] = %s\n", i, argv[i]);    }    return 0;}

編譯命令為

$ gcc pass_args.c -o pass_args

運行命令及結果如下:

$ ./pass_args arg1 arg2 3argc = 4argv[ 0 ] = ./pass_argsargv[ 1 ] = arg1argv[ 2 ] = arg2argv[ 3 ] = 3
 Python 語言

Python 語言可以使用 sys 模組中的 argv 變數, 實現相似的功能.  如果需要更進階的命令列參數傳遞方式, 可以使用 argparse 模組. 使用 sys.argv 的範例程式碼如下:

#!/usr/bin/env python# -*- coding: utf8 -*-from __future__ import print_functionimport sysif __name__ == ‘__main__‘:    print (‘The argument count is %d.‘ % len(sys.argv))    print (‘The argument vectors: ‘)    for i, arg in enumerate(sys.argv):        print (‘  argv[ %d ] = %s‘ % (i, arg))

運行命令及結果如下:

$ python pass_args.py arg1 arg2 3The argument count is 4.The argument vectors:   argv[ 0 ] = pass_args.py  argv[ 1 ] = arg1  argv[ 2 ] = arg2  argv[ 3 ] = 3

 

參考資料

1. Regarding ‘main(int argc, char *argv[])‘ [duplicate]. https://stackoverflow.com/questions/3898021/regarding-mainint-argc-char-argv

2. Entry point - Wikipedia. https://en.wikipedia.org/wiki/Entry_point

3. Python - Command Line Arguments. https://www.tutorialspoint.com/python/python_command_line_arguments.htm

 

傳遞命令列參數範例程式碼 (C 和 Python)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.