0

I have a directory where csv files are located. The code reads the files and creates histograms based on the data in the files.

However, I am trying to make it so that at the command line, I can enter one of the column headers in the csv file and the code will only make a graph of the specified command. Example: python histogram_maker.py "C:/Folder" Area.

I was able to do that, but I want to add a part that would create an error message in case the user enters a command that is not specified in the csv file. Example: Perimeter does not exist. How can I do that?

for column in df:
    os.chdir(directory)
    if len(sys.argv)>2:
        for x in arguments:
            if x.endswith(column):
                # code to make histogram

Need part that would say if x.endswith(column) not there error message should appear.

1
  • When you say "in case the user enters a command that is not specified in the csv file" do you mean "column" instead of "command"? Commented Aug 8, 2013 at 13:36

3 Answers 3

1

The standard way of issuing errors in python is with raise Exception("error message"). Or to use a subclass of Exception but in the same way. If you don't want to dump a stack track on the user, you can wrap the entire script in a try...except statement and use something like sys.stderr.write(str(e)) in the except block to just print the error message to STDERR. Then use sys.exit(1) to exit with a non-zero return code, or better use choose an appropriate return code from the errno module to pass to sys.exit.

So I would do something like this (if I understand your question):

import sys, errno

try:
    for column in df:
        os.chdir(directory)
        if len(sys.argv)>2:
            for x in arguments:
                if x.endswith(column):
                    # code to make histogram
                    pass
                else:
                    raise Exception("Perimeter does not exist")
except Exception, e:
    sys.stderr.write("Error: %s" % str(e))
    sys.exit(errno.EINVAL)

See the python documentation on errors and exceptions.

Sign up to request clarification or add additional context in comments.

Comments

0

Are you looking for this?

raise Exception("Perimeter does not exist")

Documentation

Comments

0

Use exception mechanism. Take a look at http://docs.python.org/2/reference/executionmodel.html#exceptions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.