如果没有为python shell脚本输入命令行参数,需要一种方法来忽略命令行参数

i7uaboj4  于 2023-01-26  发布在  Shell
关注(0)|答案(2)|浏览(197)

代码如下所示。当我使用指定的两个参数(user和alert)运行脚本时,脚本运行正常。但是,我需要找到一种方法,使脚本在我不提供任何参数时不会说出以下内容。
disk-monitor.py用户,警报 user, alert
如果没有提供参数,则用户值应设置为"kkelly",警报值应设置为90,脚本应使用这些值执行。

#!/usr/bin/env python3

import os
import argparse
import sys

parser = argparse.ArgumentParser()
parser.add_argument("user", help="Which user would you like to send the alert to")
parser.add_argument("alert", help="What would you like to alert set to?")
args = parser.parse_args()

if len(sys.argv) >= 2:
    # The local email account to send notifications to
    admin = args.user
    # The percentage use at which notifications will be sent
    alert = int(args.alert)
else:
    admin = "kkelly"
    alert = 90

# Capture the machine's hostname
hostname = os.popen("hostname").read().strip()
# current timestamp
date = os.popen("date").read().strip()

# Gather %use and device/filesystem of each volume
diskusage = os.popen("df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 \" \" $1 }'")
# Loop through each volume entry
for disk in diskusage.readlines():
    # Extract percentage use
    usage = os.popen("echo " + disk.strip() + " | awk '{ print $1}' | cut -d'%' -f1").read().strip()
    # extract device/filesystem name
    partition = os.popen("echo " + disk.strip() + " | awk '{ print $2 }'")
    # Convert usage into intege
    usageint = int(usage)
    partitionstring = partition.read().strip()
    # if %use of this volume is above the point at which we want to be notified...
    if usageint > alert:
        # ...send that notification
        os.system(
            "echo '" + hostname + " is running out of space on " + partitionstring + " partition.  As of " + date + " it is at " + usage + "%.' | mail -s 'Alert: " + hostname + " is almost out of disk space' " + admin)

尝试导入sys模块来检查参数,但我不太明白我在做什么。

fgw7neuy

fgw7neuy1#

它不允许你将它们设置为非必需的,即使它们有一个默认设置,原因是它们是位置参数。
如果改为将它们设置为选项,则可以使用默认值和非必需标志运行代码,如下所示:

parser.add_argument(
    "-u", "--user", help="Which user would you like to send the alert to", required=False, default="kkelly")
parser.add_argument(
    "-a", "--alert", help="What would you like to alert set to?", required=False, default="90")

这可以在下面的argparse文档中看到:)

ccrfmcuu

ccrfmcuu2#

提供默认值是不够的,还需要设置nargs='?'来标记参数为可选:

parser.add_argument("user", nargs='?', default='kkelly', help="Which user would you like to send the alert to")
parser.add_argument("alert", nargs='?', default='90', help="What would you like to alert set to?")

相关问题