7
\$\begingroup\$

I hate having to format questions around here. Adding four spaces to each source file and the correct name at the top of each source file becomes a headache when I have to post longer questions.

This is a simple python question parser that takes in arguments from the console and prints out correct format for a CodeReview question. Any suggestions on how to make this code more readable, concise and pythonic would be appreciated.

Question Parser.py

import os
import sys
import argparse

def format_string(PATH,EXTENSION):
    source_files=[f for f in os.listdir(PATH) if os.path.isfile(os.path.join(PATH,f))]
    source_files=[f for f in source_files if f.endswith(EXTENSION)]

    indentation=4
    formatted_string=""
    for source_file in source_files:
        formatted_string+= ("**%s**\n\n" % source_file)
        with open(os.path.join(PATH,source_file)) as source:
            for line in source.readlines():
                formatted_string+=(" "*indentation+"".join(line))

    return formatted_string



if __name__=="__main__":
    parser=argparse.ArgumentParser(description="Automatic formatter for CodeReview Stackexchange Questions")
    parser.add_argument("-p","--path",help="Path for the source files. Default is the current directory",nargs="?",default=os.getcwd(),const=os.getcwd()) 
    parser.add_argument("header",help="The file that is added to the top of the question")
    parser.add_argument("-e","--extension",help="Filter by the type of source files that is present in the directory",nargs="+",default="")
    parser.add_argument("-o","--out",help="Output the result to a file. By default outputs to the console.",nargs="?")
    args=parser.parse_args()

    if not os.path.isfile(args.header):
        raise parser.error("Header file doesnot exist.\nPlease specify a correct header file path")

    if os.path.exists(args.path):
        question="".join(open(args.header).readlines())
        question+="\n"+format_string(args.path,tuple(args.extension,))
        if not (args.out==None):
            with open(args.out,"w") as outfile:
                outfile.write(question)
        else:
            print(question)

    else:
        raise parser.error("Path doesnot exist.")
\$\endgroup\$
7
\$\begingroup\$

PEP 8

I would review PEP 8. Some of your style choices are not considered best practice by the Python community. Some quick observations:

  1. Constants are given CAPS_WITH_UNDERSCORES. Not function/method parameters. PATH should be path for instance.
  2. There is a space between the binary operators (there are, however, some exceptions: see Other Recommendations). So, for instance: indentation=4 should be indentation = 4.
  3. Instead of if not (args.out==None):, You should do if args.out is not None: (See Programming Recommendations)
  4. I would advise making a main function. Yes if __name__ == '__main__': is a start but I would recommend having a main function (see this answer, in particular the section "An Even Better Way"):

--

def main():        
    parser=argparse.ArgumentParser(...)
    ...

if __name__ == '__main__':
    main()
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.