windows/linux終端執行python文件並向文件傳參


windows終端執行python文件並向文件傳參


這篇文章講解一下終端命令行執行py文件,並向文件傳參的操作:

獲取終端傳遞的參數 參數格式:參數之間加空格

引入標准庫
import sys

  • 獲取操作文件的絕對目錄file_path = sys.argv[0]
  • 獲取第一個參數params_first = sys.argv[1]
  • 獲取第二個參數params_second = sys.argv[2]
  • ......

啊哈,結束了,好像有點快哦,
就是文件通過sys.argv[n]獲取終端命令傳遞的參數,然后再在其他地方引用。


  

Demo: email_log.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-   
# 以上兩行代碼在linux環境運行時一定要加上,第一行是找到python解釋器進行運行py文件,第二行解決編碼問題

"""
1 讀取log日志文件
2 正則匹配目標文本 參數1:日志中執行腳本所在目錄 參數2:ip:port 參數3:csv文件所在目錄
3 把匹配到的命令行寫入sh腳本文件進行后續執行
"""


import sys
import re
import datetime

print(sys.getdefaultencoding())  # 獲取編碼格式

script_content = "/home/dif/TDMP/app/"
csv_file_content = "/nfs2/TMP/DOWN/"
ip_port = "145.0.35.77:10025"


def read_log() :
    try:
        with open('./app.log', "r+", encoding='UTF-8') as f:
            error_content = f.read()
    except Exception as error:
        print(error)
        error_content = ''
    return error_content


def match_params(error_content):
    pattern_3 = "cd.*message-charset=utf-8$"
    pat_3 = re.compile(pattern_3, re.S)
    commond = pat_3.search(error_content).group()  # res_3獲取 shell命令行
    return commond


def replace_params(params_1=script_content, params_2=ip_port, params_3=csv_file_content):
    error_content = read_log()
    commond = match_params(error_content)
    res = commond.replace("/home/dif/TDMP/app/", params_1).replace('145.0.35.77:10025', params_2).replace("/nfs2/TMP/DOWN/", params_3)
    return res


def write_sh(res):
    now_time = datetime.datetime.now()
    time_strp = datetime.datetime(now_time.year, now_time.month, now_time.day).strftime('%Y-%m-%d')
    file_name = time_strp + "-TSMP.sh"
    with open('./'+file_name, 'wb', encoding="UTF-8") as f:
        f.write(res)
    print("生成sh命令腳本成功")
    return "done"


if __name__ == '__main__':

    instance = True  # 保證傳參格式正確
    try:
        params_1 = sys.argv[1]  # 參數1 日志中執行腳本所在目錄
    except IndexError as error:
        params_1 = script_content
        print("沒有輸入參數1,參數1使用默認值")
    try:
        params_2 = sys.argv[2]  # 參數2 ip:端口
    except IndexError as error:
        params_2 = ip_port
        print("沒有輸入參數2,參數2使用默認值")
    try:
        params_3 = sys.argv[3]  # 參數3 csv文件目錄
    except IndexError as error:
        params_3 = csv_file_content
        print("沒有輸入參數3,參數3使用默認值")

    res = replace_params(params_1, params_2, params_3)
    write_sh(res)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM