python argparse: unrecognized arguments











up vote
20
down vote

favorite
1












When I run parsePlotSens.py -s bw hehe, it says that hehe is an unrecognized argument. However, if I run parsePlotSens.py hehe -s bw, it's OK. Ideally, I would like it work for both cases.



Any tips? The following is my code:



if __name__ == '__main__' :

parser = argparse.ArgumentParser(prog='parsePlotSens');
parser.add_argument('-s', '--sort', nargs =1, action = 'store', choices = ['mcs', 'bw'], default='mcs', help=sorthelp)
parser.add_argument('filename', nargs ='+', action = 'store')
option = parser.parse_args(sys.argv)









share|improve this question




























    up vote
    20
    down vote

    favorite
    1












    When I run parsePlotSens.py -s bw hehe, it says that hehe is an unrecognized argument. However, if I run parsePlotSens.py hehe -s bw, it's OK. Ideally, I would like it work for both cases.



    Any tips? The following is my code:



    if __name__ == '__main__' :

    parser = argparse.ArgumentParser(prog='parsePlotSens');
    parser.add_argument('-s', '--sort', nargs =1, action = 'store', choices = ['mcs', 'bw'], default='mcs', help=sorthelp)
    parser.add_argument('filename', nargs ='+', action = 'store')
    option = parser.parse_args(sys.argv)









    share|improve this question


























      up vote
      20
      down vote

      favorite
      1









      up vote
      20
      down vote

      favorite
      1






      1





      When I run parsePlotSens.py -s bw hehe, it says that hehe is an unrecognized argument. However, if I run parsePlotSens.py hehe -s bw, it's OK. Ideally, I would like it work for both cases.



      Any tips? The following is my code:



      if __name__ == '__main__' :

      parser = argparse.ArgumentParser(prog='parsePlotSens');
      parser.add_argument('-s', '--sort', nargs =1, action = 'store', choices = ['mcs', 'bw'], default='mcs', help=sorthelp)
      parser.add_argument('filename', nargs ='+', action = 'store')
      option = parser.parse_args(sys.argv)









      share|improve this question















      When I run parsePlotSens.py -s bw hehe, it says that hehe is an unrecognized argument. However, if I run parsePlotSens.py hehe -s bw, it's OK. Ideally, I would like it work for both cases.



      Any tips? The following is my code:



      if __name__ == '__main__' :

      parser = argparse.ArgumentParser(prog='parsePlotSens');
      parser.add_argument('-s', '--sort', nargs =1, action = 'store', choices = ['mcs', 'bw'], default='mcs', help=sorthelp)
      parser.add_argument('filename', nargs ='+', action = 'store')
      option = parser.parse_args(sys.argv)






      python argparse






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 11 '17 at 21:56









      alex

      2,46053166




      2,46053166










      asked Jun 15 '13 at 0:14









      Yan Zhu

      1,27021330




      1,27021330
























          4 Answers
          4






          active

          oldest

          votes

















          up vote
          37
          down vote



          accepted










          Do not pass sys.argv as an argument to parse_args. Just use



          option = parser.parse_args()


          If you do pass sys.argv to parse_args, then the path or name of the script itself is the first item in sys.argv and thus becomes the value of option.filename. The hehe then becomes an unknown argument.



          If you omit sys.argv then parse_args parses sys.argv as expected.






          share|improve this answer

















          • 11




            Alternatively you can call parser.parse_args(sys.argv[1:]). Internally argparse does just that.
            – MarioVilas
            Dec 14 '13 at 1:54


















          up vote
          5
          down vote













          Also, as a complement to unutbu's answer, storing the arguments in a dictionary this way makes the tests easy:



          args = vars(parser.parse_args())
          print args


          Prints the dictionary:



          {'sort': ['bw'], 'filename': ['hehe']}


          Like :



          if args['sort'] == 'bw':
          # code here

          ...





          share|improve this answer






























            up vote
            4
            down vote













            You can get around this by allowing unknown arguments



            Replace



            args = parser.parse_args()


            with



            args, unknown = parser.parse_known_args()





            share|improve this answer




























              up vote
              0
              down vote













              My situation not same with the question, but the error is same.



              My situation:




              1. I have a remote dev(SFTP) with windows pycharm, and upload to run with linux.


              2. the python command have some line break with in my bash file, like



                python args_config.py 
                --arg1="hello"
                --arg2="world"



              and raise a python argparse: unrecognized arguments args not found error.



              the problem is the bash file line breaking is different in windows and linux,



              just setting with pycharm File -> Line Separators -> LF - Unix and OS X (n)



              upload to linux and run bash file, it works!






              share|improve this answer





















                Your Answer






                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: "1"
                };
                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: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17118999%2fpython-argparse-unrecognized-arguments%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                37
                down vote



                accepted










                Do not pass sys.argv as an argument to parse_args. Just use



                option = parser.parse_args()


                If you do pass sys.argv to parse_args, then the path or name of the script itself is the first item in sys.argv and thus becomes the value of option.filename. The hehe then becomes an unknown argument.



                If you omit sys.argv then parse_args parses sys.argv as expected.






                share|improve this answer

















                • 11




                  Alternatively you can call parser.parse_args(sys.argv[1:]). Internally argparse does just that.
                  – MarioVilas
                  Dec 14 '13 at 1:54















                up vote
                37
                down vote



                accepted










                Do not pass sys.argv as an argument to parse_args. Just use



                option = parser.parse_args()


                If you do pass sys.argv to parse_args, then the path or name of the script itself is the first item in sys.argv and thus becomes the value of option.filename. The hehe then becomes an unknown argument.



                If you omit sys.argv then parse_args parses sys.argv as expected.






                share|improve this answer

















                • 11




                  Alternatively you can call parser.parse_args(sys.argv[1:]). Internally argparse does just that.
                  – MarioVilas
                  Dec 14 '13 at 1:54













                up vote
                37
                down vote



                accepted







                up vote
                37
                down vote



                accepted






                Do not pass sys.argv as an argument to parse_args. Just use



                option = parser.parse_args()


                If you do pass sys.argv to parse_args, then the path or name of the script itself is the first item in sys.argv and thus becomes the value of option.filename. The hehe then becomes an unknown argument.



                If you omit sys.argv then parse_args parses sys.argv as expected.






                share|improve this answer












                Do not pass sys.argv as an argument to parse_args. Just use



                option = parser.parse_args()


                If you do pass sys.argv to parse_args, then the path or name of the script itself is the first item in sys.argv and thus becomes the value of option.filename. The hehe then becomes an unknown argument.



                If you omit sys.argv then parse_args parses sys.argv as expected.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jun 15 '13 at 0:35









                unutbu

                539k9911541222




                539k9911541222








                • 11




                  Alternatively you can call parser.parse_args(sys.argv[1:]). Internally argparse does just that.
                  – MarioVilas
                  Dec 14 '13 at 1:54














                • 11




                  Alternatively you can call parser.parse_args(sys.argv[1:]). Internally argparse does just that.
                  – MarioVilas
                  Dec 14 '13 at 1:54








                11




                11




                Alternatively you can call parser.parse_args(sys.argv[1:]). Internally argparse does just that.
                – MarioVilas
                Dec 14 '13 at 1:54




                Alternatively you can call parser.parse_args(sys.argv[1:]). Internally argparse does just that.
                – MarioVilas
                Dec 14 '13 at 1:54












                up vote
                5
                down vote













                Also, as a complement to unutbu's answer, storing the arguments in a dictionary this way makes the tests easy:



                args = vars(parser.parse_args())
                print args


                Prints the dictionary:



                {'sort': ['bw'], 'filename': ['hehe']}


                Like :



                if args['sort'] == 'bw':
                # code here

                ...





                share|improve this answer



























                  up vote
                  5
                  down vote













                  Also, as a complement to unutbu's answer, storing the arguments in a dictionary this way makes the tests easy:



                  args = vars(parser.parse_args())
                  print args


                  Prints the dictionary:



                  {'sort': ['bw'], 'filename': ['hehe']}


                  Like :



                  if args['sort'] == 'bw':
                  # code here

                  ...





                  share|improve this answer

























                    up vote
                    5
                    down vote










                    up vote
                    5
                    down vote









                    Also, as a complement to unutbu's answer, storing the arguments in a dictionary this way makes the tests easy:



                    args = vars(parser.parse_args())
                    print args


                    Prints the dictionary:



                    {'sort': ['bw'], 'filename': ['hehe']}


                    Like :



                    if args['sort'] == 'bw':
                    # code here

                    ...





                    share|improve this answer














                    Also, as a complement to unutbu's answer, storing the arguments in a dictionary this way makes the tests easy:



                    args = vars(parser.parse_args())
                    print args


                    Prints the dictionary:



                    {'sort': ['bw'], 'filename': ['hehe']}


                    Like :



                    if args['sort'] == 'bw':
                    # code here

                    ...






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 15 '13 at 0:41

























                    answered Jun 15 '13 at 0:24









                    Gauthier Boaglio

                    7,68523567




                    7,68523567






















                        up vote
                        4
                        down vote













                        You can get around this by allowing unknown arguments



                        Replace



                        args = parser.parse_args()


                        with



                        args, unknown = parser.parse_known_args()





                        share|improve this answer

























                          up vote
                          4
                          down vote













                          You can get around this by allowing unknown arguments



                          Replace



                          args = parser.parse_args()


                          with



                          args, unknown = parser.parse_known_args()





                          share|improve this answer























                            up vote
                            4
                            down vote










                            up vote
                            4
                            down vote









                            You can get around this by allowing unknown arguments



                            Replace



                            args = parser.parse_args()


                            with



                            args, unknown = parser.parse_known_args()





                            share|improve this answer












                            You can get around this by allowing unknown arguments



                            Replace



                            args = parser.parse_args()


                            with



                            args, unknown = parser.parse_known_args()






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 2 at 7:58









                            FacePalm

                            2,37922230




                            2,37922230






















                                up vote
                                0
                                down vote













                                My situation not same with the question, but the error is same.



                                My situation:




                                1. I have a remote dev(SFTP) with windows pycharm, and upload to run with linux.


                                2. the python command have some line break with in my bash file, like



                                  python args_config.py 
                                  --arg1="hello"
                                  --arg2="world"



                                and raise a python argparse: unrecognized arguments args not found error.



                                the problem is the bash file line breaking is different in windows and linux,



                                just setting with pycharm File -> Line Separators -> LF - Unix and OS X (n)



                                upload to linux and run bash file, it works!






                                share|improve this answer

























                                  up vote
                                  0
                                  down vote













                                  My situation not same with the question, but the error is same.



                                  My situation:




                                  1. I have a remote dev(SFTP) with windows pycharm, and upload to run with linux.


                                  2. the python command have some line break with in my bash file, like



                                    python args_config.py 
                                    --arg1="hello"
                                    --arg2="world"



                                  and raise a python argparse: unrecognized arguments args not found error.



                                  the problem is the bash file line breaking is different in windows and linux,



                                  just setting with pycharm File -> Line Separators -> LF - Unix and OS X (n)



                                  upload to linux and run bash file, it works!






                                  share|improve this answer























                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    My situation not same with the question, but the error is same.



                                    My situation:




                                    1. I have a remote dev(SFTP) with windows pycharm, and upload to run with linux.


                                    2. the python command have some line break with in my bash file, like



                                      python args_config.py 
                                      --arg1="hello"
                                      --arg2="world"



                                    and raise a python argparse: unrecognized arguments args not found error.



                                    the problem is the bash file line breaking is different in windows and linux,



                                    just setting with pycharm File -> Line Separators -> LF - Unix and OS X (n)



                                    upload to linux and run bash file, it works!






                                    share|improve this answer












                                    My situation not same with the question, but the error is same.



                                    My situation:




                                    1. I have a remote dev(SFTP) with windows pycharm, and upload to run with linux.


                                    2. the python command have some line break with in my bash file, like



                                      python args_config.py 
                                      --arg1="hello"
                                      --arg2="world"



                                    and raise a python argparse: unrecognized arguments args not found error.



                                    the problem is the bash file line breaking is different in windows and linux,



                                    just setting with pycharm File -> Line Separators -> LF - Unix and OS X (n)



                                    upload to linux and run bash file, it works!







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 10 at 8:56









                                    Colin Wang

                                    15124




                                    15124






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17118999%2fpython-argparse-unrecognized-arguments%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Schultheiß

                                        Liste der Kulturdenkmale in Wilsdruff

                                        Android Play Services Check