Python tool to assemble CodeReview posts from source files

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
7
down vote

favorite
2












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**nn" % 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.")









share|improve this question





























    up vote
    7
    down vote

    favorite
    2












    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**nn" % 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.")









    share|improve this question

























      up vote
      7
      down vote

      favorite
      2









      up vote
      7
      down vote

      favorite
      2






      2





      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**nn" % 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.")









      share|improve this question















      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**nn" % 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.")






      python file formatting stackexchange






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 2 at 5:45

























      asked Sep 2 at 5:26









      Gnik

      15010




      15010




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          7
          down vote



          accepted










          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()





          share|improve this answer




















            Your Answer




            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            );
            );
            , "mathjax-editing");

            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: false,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f202968%2fpython-tool-to-assemble-codereview-posts-from-source-files%23new-answer', 'question_page');

            );

            Post as a guest






























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            7
            down vote



            accepted










            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()





            share|improve this answer
























              up vote
              7
              down vote



              accepted










              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()





              share|improve this answer






















                up vote
                7
                down vote



                accepted







                up vote
                7
                down vote



                accepted






                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()





                share|improve this answer












                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()






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Sep 2 at 5:54









                Dair

                4,208727




                4,208727



























                     

                    draft saved


                    draft discarded















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f202968%2fpython-tool-to-assemble-codereview-posts-from-source-files%23new-answer', 'question_page');

                    );

                    Post as a guest













































































                    這個網誌中的熱門文章

                    Is there any way to eliminate the singular point to solve this integral by hand or by approximations?

                    Why am i infinitely getting the same tweet with the Twitter Search API?

                    Amount of Number Combinations to Reach a Sum of 10 With Integers 1-9 Using 2 or More Integers [closed]