What is wrong with this python script?

I have this code:

from sys import argv
import os
bold = "\033[1m"
reset = "\033[0;0m"
try: argv[1]
except IndexError: print("\nNo arguments! Add \"-h\" or \"--help\" for more info." + bold + "\n\nNow look what you've done!" + reset)
else: pass
if argv[1] == "-h" or "--help": print("\nxxxx, version 0.0.2") print("xxxx is a simple tool for the command line used for quickly saving\n\
chunks of text, while providing more functionality than the traditional method\n\
(e.g. echo \"HELLO WORLD\" > hi.txt) used in bash.") print("\nUsage: sans-sheriff [text] [directory] [options]") print("\nOptions:\n\ -h, --help Display this help message and exit.\n\ -v, --verbose Output more verbosity.\n\ -e=utf8, --encoding Sets the encoding. Default is utf-8.\n\ utf16\n\ utf32\n\ ascii\n\ iso (8859-1)\n\
-text Sets the filetype. Default is \".txt\".\n\ html\n\ rtf\n\ tex\n\
-o, --open Open the file directly after.\n\
\n\
e.g. xxxx \"Hello World\" /home/user/Documents/myfile -e=utf32")
else: try: argv[2] except IndexError: print("No directory argument! Add \"-h\" or \"--help\" fopr mor info." + bold + "\n\nNow look what you've done!" + reset) else: pass usrtxt = argv[1] usrdir = argv[2] usrtxt = open(usrdir, "w")

It is supposed to create text files based on a users' arguments, like this:

xxxx \"Hello World\" /home/user/Documents/myfile

But whenever it is launched like the example provided, it just loads the output that would have been produced when -h or --help is argued... It doesn't seem logical why it would do this, and I'm quite a newbie to python as well, so any help would be greatly appreciated!

1 Answer

You're using or incorrectly. The proper way to do this in your example would be:

if argv[1] == "-h" or argv[1] == "--help":

Or is a Boolean operator that describes what to do with two different comparisons. So what you have provided would be like saying

keep_going = False
if argv[1] == "-h": keep_going = True
if "--help": keep_going = True

Which doesn't make sense. Technically just having or "--help" is True because "--help" is a non-empty String.

In addition, thanks to Timo, you could use

if argv[1] in ("-h", "--help"):

Which is considered more the Python way

Lastly, you should be looking in to things like argparse for Python to properly handle arguments as they may not always be in the same order.

In the future, questions strictly regarding code are better suited for Stack Overflow which is likely better suited for programming questions.

5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like