Note: shell scrip 與python code的合併使用(via sys.argv[]) ================================================================================= 工作上基於方便,寫了一支`shell script`整理log,又為了將log內容自動對照指標數據,寫了一支 `python`code 事後想想,怎麼不乾脆串起來一起跑?這邊就引用以下酷東西,將log檔名作為參數傳遞至python code: ```python= import sys sys.argv[] ``` Syntax --------------------------------------------------------------------------------- 節錄shell script: ```bash= [[ -z "$file" || "$file" == \#* ]] && continue $cmd "$key_1" "$file" >> "$log" $cmd "$key_2" "$file" >> "$log" python3 ref.py $file done ``` 根據上面的code可知,`ref.py`是打算直接吃到script中的`$file`參數 使用`sys.argv[]`,將`$file`作為python code的輸出,語法如下: ```python= import sys print(sys.argv[n]) ``` 其中,n值是一個整數,分別是以下含意: | 索引 | 內容 | 範例輸入 | 對應值 | |---------------|-------------------------------|----------------------------------------|------------------| | `sys.argv[0]` | 執行的 Python 檔案名稱 | `python3 my_script.py input.txt` | `"my_script.py"` | | `sys.argv[1]` | 第一個參數(使用者傳入) | | `"input.txt"` | | `sys.argv[2]` | 第二個參數 | `python3 my_script.py a.txt 123` | `"123"` | | ... | 更多參數(都是字串) | | | Demo code --------------------------------------------------------------------------------- 最後將`sys.argv`帶入`if-loop`中使用,利用傳入值n<2的特性,如下: ```python= import sys if len(sys.argv)<2: print("Usage: python3 ref.py <log_file>") sys.exit(1) ``` Ref. --------------------------------------------------------------------------------- [Python中 sys.argv[]的用法简明解释](https://www.cnblogs.com/aland-1415/p/6613449.html) [Python 中 sys.argv 用法详解](https://blog.csdn.net/fancynthia/article/details/126271660)