Kmom06 - Kombination av opts och args

  • Författare
  • Meddelande

EmelieK

javascript-guru

  • Inlägg: 89
  • Blev medlem: 16 aug 2016, 16:31

Kmom06 - Kombination av opts och args

Inlägg17 okt 2016, 17:23

Hej,

Jag tycks få problem när jag ska ange både argument och options på kommandoraden. Skriver jag till exempel in bara seo tillsammans med en url går det bra, men om jag skriver -j eller --json seo <url> får jag "Missing command" som resultat. Jättetacksam för hjälp, har nog inte förstått detta fullt ut. :(

Min kod:
Kod: Markera allt
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Marvin the chatbot.

"""

import sys
import os
import requests
from datetime import datetime
import getopt
from bs4 import BeautifulSoup
import json
import random


#About this program
PROGRAM = os.path.basename(sys.argv[0])
AUTHOR = "Emelie Kjellson"
VERSION = "1.0.0"
USAGE = """{program} - Marvin. By {author}, version {version}.

Usage:
  {program} [options] name
 
  Commands:
  ping <url>                     Ping given url for current status.       
  ping-history                   Print log file of pinged websites.
  get <url>                      Get content of given url.
  quote                          Get random quote.   
 
  Options:
  -h --help                      Display this help message.
  --debug                        Display extra details or statistics about the execution.
  -s --silent                    Do not display any details or statistics about the execution.
  -v --version                   Print version and exit.
  --output <file>                Change output to file. 
  --input <file>                 Change input to file.
""".format(program=PROGRAM, author=AUTHOR, version=VERSION)

MSG_VERSION = "{program} version {version}.".format(program=PROGRAM, version=VERSION)
MSG_USAGE = "Use {program} --help to get usage.\n".format(program=PROGRAM)


#
# Global default settings affecting behaviour of script in several places
#
VERBOSE = True
DEBUG = False
OUTPUT = False
INPUT = False
OUTPUTFILE = ""
INPUTFILE = ""
JSONFORMAT = False

EXIT_SUCCESS = 0
EXIT_USAGE = 1
EXIT_FAILED = 2


def printUsage(exitStatus):
    """
    Print usage information about the script and exit.
    """
    print(USAGE)
    sys.exit(exitStatus)


def printVersion():
    """
    Print version information and exit.
    """
    print(MSG_VERSION)
    sys.exit(EXIT_SUCCESS)


def pingWebsite(url):
    """
    Get status from given url. 
    """
   
    try:
        # Get current time
        checkTime = datetime.now()
       
        # Request header from url
        req = requests.head(url)
       
        # Writes status to file
        with open('ping-history.txt', 'a') as fin:
            fin.write("{0}: Recieved status code of {1}: {2}\n".format(checkTime, url, req.status_code))
   
        # Print result
        print("Recieved status code: ", req.status_code)
        if VERBOSE:
            print("Request to ", url, " sent at ", checkTime)
            print("Page was last modified: ", req.headers["Last-Modified"])
   
   
    except requests.ConnectionError:
        print("Failed to connect")
       
       
def viewLog():
    """
    Prints content of ping-history.txt.
    """
    if os.stat('ping-history.txt').st_size > 0:
        with open('ping-history.txt', 'r') as fin:
            print(fin.read())
    else:
        print("\nThe log file is currently empty.")
       
       
def getWebsite(url):
    """
    Prints content of given website.
    """
    req = requests.get(url)
    content = BeautifulSoup(req.text, "html.parser")
   
    if OUTPUT:
        if os.path.isfile(OUTPUTFILE):
            with open(OUTPUTFILE, 'w') as fin:
                fin.write(content)
            if VERBOSE:
                print("\nOutput printed to file.\n")
        else:
            print("File not found.")
    else:
        print(content)
       
       
def getWebsiteTitle(url):
    """
    Prints title of given website or html-file.
    """
    if INPUT:
        if os.path.isfile(INPUTFILE):
            with open(INPUTFILE, 'r') as fin:
                content = BeautifulSoup(fin.text, "html.parser")
                title = content.title.string
                if VERBOSE:
                    print("Input from file.\n")
                print("The title of the requested website is:  {0}\n".format(title))
        else:
            print("File not found.")
    else:
        req = requests.get(url)
        content = BeautifulSoup(req.text, "html.parser")
        title = content.title.string
        print("\nThe title of the requested website is:  {0}\n".format(title))
       
       
def analyzeWebsite(url):
    """
    SEO-analyzes given website or html-file.
    """
    if INPUT:
        if os.path.isfile(INPUTFILE):
            with open(INPUTFILE, 'r') as fin:
                content = BeautifulSoup(fin.text, "html.parser")
                #title = content.title.string
                if VERBOSE:
                    print("Input from file.\n")
                #print("The title of the requested website is:  {0}\n".format(title))
        else:
            print("File not found.")
    else:
        req = requests.get(url)
        content = BeautifulSoup(req.text, "html.parser")
        title = content.title.string
        if JSONFORMAT:
            jsonobject = ["SEO-Analysis"]({
                "Titles": len(content.find_all("title")),
                "Title length": len(title),
                "h1": len(content.find_all("h1")),
                "h2": len(content.find_all("h2")),
                "a": len(content.find_all("a"))
            })
            print(json.dump(jsonobject, indent=4))
        else:
            print("\nThe requested website has the following attributes:")
            print("1) There is/are {} title/titles.".format(len(content.find_all("title"))))
            print("2) The title of the requested website is {0} characters long.".format(len(title)))
            print("3) There is/are {} first level headline/-s, e.g. <h1>-tags.".format(len(content.find_all("h1"))))
            print("4) There is/are {} second level headline/-s, e.g. <h2>-tags.".format(len(content.find_all("h2"))))
            print("5) There is/are {} link/-s, e.g. <a>-tags.\n".format(len(content.find_all("a"))))
       
       
def getQuote():
    """
    Prints quote fetched from website of from file.
    """
    if INPUT:
        if os.path.isfile(INPUTFILE):
            with open(INPUTFILE, 'r') as fin:
                quotes = json.load(fin)
                if VERBOSE:
                    print("Input from file.\n")
                print("Quote of today is:")
                print(random.choice(quotes["quotes"]) + "\n")
        else:
            print("File not found.")
    else:
        req = requests.get('http://dbwebb.se/javascript/lekplats/get-marvin-quotes-using-ajax/quote.php')
        jsonobject = req.json()
        print("\nQuote of today is:\n\"{quote}\"\n".format(quote=jsonobject["quote"]))
       

def parseOptions():
    """
    Merge default options with incoming options and arguments and return them as a dictionary.
    """

    # Switch through all options
    try:
        global VERBOSE, DEBUG, OUTPUT, INPUT, OUTPUTFILE, INPUTFILE, JSONFORMAT

        opts, args = getopt.getopt(sys.argv[1:], "hi:jo:sv", ["help", "silent", "verbose", "version", "output=", "input=", "json"])

        for opt, args in opts:
            if opt in ("-h", "--help"):
                printUsage(EXIT_SUCCESS)

            elif opt in ("-s", "--silent"):
                VERBOSE = False
               
            elif opt in ("--verbose"):
                DEBUG = True

            elif opt in ("-v", "--version"):
                printVersion()
               
            elif opt in ("-o", "--output"):
                OUTPUT = True
                OUTPUTFILE = args
               
            elif opt in ("-i", "--input"):
                INPUT = True
                INPUTFILE = args
               
            elif opt in ("-j", "--json"):
                JSONFORMAT = True
               
            else:
                assert False, "Unhandled option"
       
        if len(args) < 1:
            assert False, "Missing command"
           
        else:
            if 'ping' in args:
                 pingWebsite(args[len(args)-1])
           
            elif 'ping-history' in args:
                viewLog()
               
            elif 'get' in args:
                getWebsite(args[len(args)-1])
               
            elif 'quote' in args:
                getQuote()
               
            elif 'title' in args:
                getWebsiteTitle(args[len(args)-1])
           
            elif 'seo' in args:
                analyzeWebsite(args[len(args)-1])
           

    except Exception as err:
        print(err)
        print(MSG_USAGE)
        # Prints the callstack, good for debugging, comment out for production
        #traceback.print_exception(Exception, err, None)
        sys.exit(EXIT_USAGE)




def main():
    """
    Main function to carry out the work.
    """
    startTime = datetime.now()
    if DEBUG:
        print("Script started at {0}.".format(startTime))

    parseOptions()

    timediff = datetime.now()-startTime
    if VERBOSE:
        sys.stderr.write("Script executed in {}.{} seconds\n".format(timediff.seconds, timediff.microseconds))

    sys.exit(EXIT_SUCCESS)



if __name__ == "__main__":
    main()
Användarvisningsbild

mos

dbwebb

  • Inlägg: 10922
  • Blev medlem: 10 nov 2011, 09:52
  • Ort: Ronneby / Bankeryd

Re: Kmom06 - Kombination av opts och args

Inlägg17 okt 2016, 17:33

Du har följande rad:
Kod: Markera allt
        for opt, args in opts:


Kan vara så att args där borde vara arg.

Annars skriver du över variabeln args som du skapade i raden ovanför.

Variabeln args innehåller alltså inte det som du trodde när du kommer längre ned i koden.
https://github.com/dbwebb-se/python/blo ... s2.py#L123
...
..:
.... /mos

EmelieK

javascript-guru

  • Inlägg: 89
  • Blev medlem: 16 aug 2016, 16:31

Re: Kmom06 - Kombination av opts och args

Inlägg17 okt 2016, 18:49

Tusen, tusen tack! Det löste allting!!!

Vilka är online

Användare som besöker denna kategori: Inga registrerade användare och 12 gäster