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