0

I just finished week 6 lecture and I'm doing the practice problems. I'm stuck with FIGlet, I don't understand why I get the timeout error message with check50 :/

check50 results

from pyfiglet import Figlet
from sys import argv
import sys
import random

figlet = Figlet()

string = input("Input: ")

# the user would like to output text in a random font.
if len(sys.argv) == 1:
    figlet.setFont(font=random.choice(font_list))
    print(f"Output: {figlet.renderText(string)}")

# the user would like to output text in a specific font
elif len(sys.argv) == 3 and (argv[1] == "-f" or argv[1] == "--font"):

    if argv[2] in figlet.getFonts():
        figlet.setFont(font=argv[2])
        print(f"Output: {figlet.renderText(string)}")
    else:
        sys.exit("Invalid usage")

# otherwise error
else:
    sys.exit("Invalid usage")

the program works as intended when I do the tests.. Can you please help me out? It's only my second attempt at python so if you also have tips on how to make the code better I would appreciate it!

2 Answers2

0

Don't ask for input when the arguments are invalid. Check the arguments first, then ask for input and print the result at the end.

from pyfiglet import Figlet
from sys import argv
import sys
import random

figlet = Figlet()

# the user would like to output text in a random font.
if len(sys.argv) == 1:
    figlet.setFont(font=random.choice(font_list))

# the user would like to output text in a specific font
elif len(sys.argv) == 3 and (argv[1] == "-f" or argv[1] == "--font"):
    if argv[2] in figlet.getFonts():
        figlet.setFont(font=argv[2])
    else:
        sys.exit("Invalid usage")

# otherwise error
else:
    sys.exit("Invalid usage")

string = input("Input: ")
print(f"Output: {figlet.renderText(string)}")

It's timing out because check50 doesn't provide any input when it gives invalid arguments, so the script is waiting forever for that.

Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

It should exit immediately after incorrect command-line arguments passed in. so you have to move your code inside the try/catch block and you have to take input after that.

try:
    if len(sys.argv) == 1:
         something something

    elif len(sys.argv) == 3 and (argv[1] == "-f" or argv[1] == "--font"):
        somtthing
    
    else:
       sys.exit("Invalid usage")
except:
    sys.exit("Invalid usage")

string = input("Input : ")
print(figlet.renderText(string))
Jay
  • 1
  • 2
  • 1
    What is the purpose of the try-catch block? What exception is it designed to catch? Could you point out which line and what part of the code is supposed to raise an exception? – Joshua Shew Aug 21 '23 at 09:27
  • @JoshuaShew In this particular code, I guess it's fine if you don't use try and catch block .but it's good practice to use it, cause it gracefully handles unexpected situations without crashing.... – Jay Aug 26 '23 at 14:00