Search code examples
pythonmysqlcommand-lineoptparse

Optparse to find a string


I have a mysql database and I am trying to print all the test result from a specific student. I am trying to create a command line where I enter the username and then it will shows his/her test result. I visited this page already but I couldn't get my answer. optparse and strings

  #after connecting to mysql
  cursor.execute("select * from database")
  def main():

     parser = optparse.OptionParser()
     parser.add_option("-n", "--name", type="string", help = "student name")
     (options, args) = parser.parse_args()

     studentinfo = []

     f = open("Index", "r")
     #Index is inside database, it is a folder holds all kinds of files

Solution

  • Well, the first thing you should do is not use optparse, as it's deprecated - use argparse instead. The help I linked you to is quite useful and informative, guiding you through creating a parser and setting the different options. After reading through it you should have no problem accessing the variables passed from the command line.

    However, there are other errors in your script as well that will prevent it from running. First, you can't open a directory with the open() command - you need to use os.listdir() for that, then read the resulting list of files. It is also very much advisable to use a context manager when open()ing files:

    filelist = os.listdir("/path/to/Index")
    for filename in filelist:
        with open(filename, "r") as f:
            for line in f:
                # do stuff with each line
    

    This way you don't need to worry about closing the file handler later on, and it's just a generally cleaner way of doing things.

    You don't provide enough information in your question as to how to get the student's scores, so I'm afraid I can't help you there. You'll (I assume) have to connect the data that's coming out of your database query with the files (and their contents) in the Index directory. I suspect that if the student scores are kept in the DB, then you'll need to retrieve them from the DB using SQL, instead of trying to read raw files in the filesystem. You can easily get the student of interest's name from the command line, but then you'll have to interpolate that into a SQL query to find the correct table, select the rows from the table corresponding to the student's test scores, then process the results with Python to print out a pretty summary.

    Good luck!