python 3.x – Argparse Error Handling – Display custom help and exit

I want the following script to exit after printing the custom help when the user incorrectly enters the required CLI arguments:

–remote_host google.com –verbose 0 (or verbose 1 for full verbosity…)

or

–help

How should this be done?

#!/usr/bin/env python

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import argparse
import sys
from scapy.all import *

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--remote_host")
parser.add_argument("--verbose")
parser.add_argument("--help", action='store_true')
args = parser.parse_args()

if args.help:
    print("Custom Help Section...")
    exit()
 
# Define end host and TCP port range
hostInput    = args.remote_host
host  = socket.gethostbyname(hostInput)
port_range = (21,22,23,25,53,80,110,135,137,138,139,443,1433,1434,8080)

# Send SYN with random Src Port for each Dst port
for dst_port in port_range:
    src_port = random.randint(1025,65534)
    resp = sr1(
        IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=1,
        verbose=int(args.verbose),
    )

    if resp is None:
        print(f"{host}:{dst_port} is filtered (silently dropped).")

    elif(resp.haslayer(TCP)):
        if(resp.getlayer(TCP).flags == 0x12):
            # Send a gratuitous RST to close the connection
            send_rst = sr(
                IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags='R'),
                timeout=1,
                verbose=int(args.verbose),
            )
            print(f"{host}:{dst_port} is open.")

        elif (resp.getlayer(TCP).flags == 0x14):
            print(f"{host}:{dst_port} is closed.")

    elif(resp.haslayer(ICMP)):
        if(
            int(resp.getlayer(ICMP).type) == 3 and
            int(resp.getlayer(ICMP).code) in (1,2,3,9,10,13)
        ):
            print(f"{host}:{dst_port} is filtered (silently dropped).")

python – Erro no script para ler arquivos e importar para banco de dados Mysql com Pandas e SqlALchemy + argparse

Estou tentando criar um programa python que insere dados em um banco de dados Mysql, mas estou recebendo o erro `TypeError: 'str' object is not callable`

from argparse import ArgumentParser
import argparse
import sqlalchemy
import pymysql as MYSQLdb
import pandas as pd

parser = ArgumentParser(prog="INSERT dados teste",
                        usage = "... -dr  (Driver)... (Usuário)... (Senha)... (IP-servidor)... (Porta)... (Nome BANCO DE DADOS)",
                        description = "Este script é usado para criar uma conexão com o MYSQLdb e inserir dados no banco",
                        epilog = "Por padrão do mysql (Porta) é a 3306 | No (Usuario) você pode usar root caso não tenha um nome pré-definido| No (IP-servidor) você pode usar 127.0.0.1 ou localhost")


parser.add_argument('-dr', "--drive", action="store", type=str, help="Nome do drive, por exemplo, pymysql.",dest="Drive",required=True)
parser.add_argument('-user', "--usuario", action="store", type=str, help="Nome do usuario, pode usar root caso não haja algum pré-definido.",dest="NomeUsario",required=True)
parser.add_argument('-s', "--senha", action="store", type =str,help="Senha do root",dest="Senha",required=True)
parser.add_argument('-ip', "--ipservidor",action = "store", type=str,help="Número de ip do servidor ou localhost",dest="Ipdoservidor",required=True)
parser.add_argument('-p', "--porta", action="store",type=str,dest="Porta",required=True)
parser.add_argument('-db', "--nomedb", action="store",type=str,help="Nome do banco de dados",dest="bancodedados",required=True)

parser.add_argument("-f",action="store", type=argparse.FileType("r"), dest="file", help="recebe um arquivo",required=True)

args = parser.parse_args()
parser.print_help()

#Conexão com sqlalchemy
try:
    #Conexão com o banco de dados - Sintaxe engine = sqlalchemy.create_engine( ‘mysql+drive://usuario:senha@ip-servidor:porta/banco-de-dados
    Drive = args.Drive
    NomeUsario = args.NomeUsario
    Senha = args.Senha
    Ipdoservidor = args.Ipdoservidor
    Porta = args.Porta
    bancodedados = args.bancodedados

    engine = sqlalchemy.create_engine='mysql+{}://{}:{}@{}:{}/{}'.format(Drive, NomeUsario, Senha, Ipdoservidor, Porta, bancodedados)
    print("Conectado")
except Exception as e: 
    print(str(e)) 
    print("Falha na conexão")   

#Abrindo/Lendo arquivos csv com pandas 

dados = pd.read_csv(args.file)
print(dados)

#Inserindo dados no banco de dados com o método to.sql() - dados.to_sql('nomedatabela', con= engine,if_exists = 'append', chunksize = 10)

dados.to_sql('tabelateste', con = engine, if_exists = 'append', chunksize = 10)

Não sei o que significa o erro e como corrigi-lo

python – usar argparse con archivo json

tengo un mi proyecto en python y mi intención es usar argparse para que según el parametro que yo le pase por la terminal me traiga datos especificos desde un archivo json. He creado algunos argumentos con argparse pero no logro hacerlos funcionar correctamente. tengo este archivo json:

{
  "services": (
    {
      "name": "ac",
      "version": "1.0.8",
      "service": "running",
      "url": "https://portal.azure.com/#home",
      "disk usage": "20%"
    },
    {
      "name": "acc",
      "version": "1.0.8",
      "service": "running",
      "url": "https://portal.azure.com/#home",
      "disk usage": "63%"
    },
    {
      "name": "acv",
      "version": "1.0.8",
      "service": "running",
      "url": "https://portal.azure.com/#home",
      "disk usage": "37%"
    },
    {
      "name": "acf",
      "version": "1.0.8",
      "service": "running",
      "url": "https://portal.azure.com/#home",
      "disk usage": "48%"
    },
    {
      "name": "ach",
      "version": "1.0.8",
      "service": "error",
      "url": "https://portal.azure.com/#home",
      "disk usage": "10%"
    },
    {
      "name": "acj",
      "version": "1.0.8",
      "service": "stopped",
      "url": "https://portal.azure.com/#home",
      "disk usage": "23%"
    },
    {
      "name": "acq",
      "version": "1.0.8",
      "service": "running",
      "url": "https://portal.azure.com/#home",
      "disk usage": "65%"
    },
    {
      "name": "bc",
      "version": "1.0.8",
      "service": "stopped",
      "url": "https://portal.azure.com/#home",
      "disk usage": "20%"
    },
        {
      "name": "bcc",
      "version": "1.0.8",
      "service": "running",
      "url": "https://portal.azure.com/#home",
      "disk usage": "25%"
    },
    {
      "name": "bcx",
      "version": "1.0.8",
      "service": "error",
      "url": "https://portal.azure.com/#home",
      "disk usage": "4%"
    },
    {
      "name": "bcn",
      "version": "1.0.8",
      "service": "running",
      "url": "https://portal.azure.com/#home",
      "disk usage": "50%"
    },
    {
      "name": "bcm",
      "version": "1.0.8",
      "service": "stopped",
      "url": "https://portal.azure.com/#home",
      "disk usage": "35%"
    }
  )
}

entonces lo que yo quiero hacer es por ejemplor ejecutando mi programa desde la terminal y usando el paramentro -s services por ejemplo es traer solamente los servicios desde el json file o si pongo -d diskusage traers solo el uso de los discos.
tengo estos parametros hasta ahora creados y hice estas def pero al ejecutar el programa me trae tanto servicios como discos

import json
import argparse
import logging


#open json data
with open('services.json') as f:
    data = json.load(f)

    def add_argument(data):
        print('Services:')
    for service in data('services'):
        print(service('name'))

def print_service_disk_usages(data):
    print('Disk Usage:')
    for service in data('services'):
        print(f'{service("name")}:t{service("disk usage")}')

#argparse parameters config
parser = argparse.ArgumentParser()
parser.add_argument("-f",
                    "--fullreport",
                    help="printing the full report",
                    default="*")
parser.add_argument("-g",
                    "--graphreport",
                    help="printing the graph report",
                    default="*")
parser.add_argument("-s",
                    "--services",
                    help="services to be test",
                    default=add_argument(data))
parser.add_argument("-d",
                    "--diskusage",
                    help="see the disk usage",
                    default=print_service_disk_usages(data))

args = parser.parse_args()

la verdad es que soy bastante nuevo en esto de scriptear en python pero agradezco su ayuda.

Automatically overwrite python – PyYaml – yaml file with the inserted argparse parameters

what i load a yaml file and update it with argparse. What is your feedback on automatically updating YAML parameters without checking that the argparse parameter is set to None
There are nearly 20 configuration parameters that I have to set to 20 with this latest version if Conditions.

The output of yaml.save_load is:

import os
import argparse
import yaml
Import feature tools
import datetime

Parser = argparse.ArgumentParser ()
parser.add_argument (
"--Config"
nargs = "?",
type = str,
default = "p.yml",
help = "configuration file to use",
)
parser.add_argument (& # 39; - learning_rate & # 39 ;, type = float, default = 0,001, help = & # 39; rate of learning rate & # 39;)

args = parser.parse_args ()


def yaml_dump (file path, data):
"" "
Write data in yaml file in file path
: param file path:
: param data:
: back: void
"" "
with open (file path & # 39; w & # 39;) as file descriptor:
yaml.safe_dump (data, file_descriptor)


def yaml_loader (file path):
"" "
Download the yaml file
: param file path:
: return: Configuration of the yaml file
"" "
with open (file path, "r") as file descriptor:
Returns yaml.safe_load (file_descriptor)


cfg = yaml_loader (args.config)
if args.learning_rate is not None:
cfg['training']['optimizer']['lr']    = args.learning_rate


ts = str (datetime.datetime.now ()). split (".")[0].replace ("", "_")
ts = ts.replace (":", "_"). replace ("-", "_")
logdir = os.path.join ("running", os.path.basename (args.config)[:-4]ts)
yaml_dump (os.path.join (logdir, args.config.split (& # 39; / & # 39;)[-1]cfg)

Here is the content of p.yaml File:

Model:
Bow: Fcn8s
Dates:
Record: Pascal
train_split: train
val_split: val
img_rows: "equal"
img_cols: "equal"
Path: VOC /
sbd_path: VOC / benchmark_RELEASE /
Training:
train_iters: 300000
batch_size: 1
val_interval: 1000
n_workers: 16
Print interval: 50
Optimizer:
name: & # 39; sgd & # 39;
Lr: 1.0e-10
Weight_decay: 0.0005
Pulse: 0.99
Loss:
name: & # 39; cross_entropy & # 39;
size_average: Wrong
lr_schedule:
CV: fcn8s_pascal_best_model.pkl