Noob question regarding sys.argv[]

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TMS
    New Member
    • Sep 2006
    • 119

    Noob question regarding sys.argv[]

    I'm completely new to Python, never wrote a C program, but I have written in C++. I've never used argv, but an assignment is requiring me to learn it and use it now. I'm using Python 2.5, IDLE (for writing code), using Win XP pro environment (can't get my Ubuntu to see my wireless card).

    I'm supposed to write a module that will take an argument from the command line that will read a file and process it. I really don't know how to do this and would appreciate a spoon fed version tutorial.

    Help, Please?
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by TMS
    I'm completely new to Python, never wrote a C program, but I have written in C++. I've never used argv, but an assignment is requiring me to learn it and use it now. I'm using Python 2.5, IDLE (for writing code), using Win XP pro environment (can't get my Ubuntu to see my wireless card).

    I'm supposed to write a module that will take an argument from the command line that will read a file and process it. I really don't know how to do this and would appreciate a spoon fed version tutorial.

    Help, Please?
    in a file (say myModule.py)
    Code:
    import sys
    for arg in sys.argv:
        print arg    # the zeroth element is the module name
    raw_input("press any key")    # a trick to keep the python console open
    (of course python must be in PATH e.v.)
    from the command line (IDLE won't do this) type

    python myModule.py any number of args

    The raw_input() call is not needed if your command-line console does not invoke a separate window for the python process (the way that Start->Run does).

    Comment

    • TMS
      New Member
      • Sep 2006
      • 119

      #3
      ok, so say my file name is file.txt (should it be formatted differently, like .py?). That is my arg, right? so:

      python myModule.py file.txt

      should call the module to call the text file, right?

      I appreciate your patience. I've been trying to work this out all day, and I know it should be obvious, but for some reason it isn't.

      Comment

      • ghostdog74
        Recognized Expert Contributor
        • Apr 2006
        • 511

        #4
        Originally posted by TMS
        ok, so say my file name is file.txt (should it be formatted differently, like .py?). That is my arg, right? so:

        python myModule.py file.txt

        should call the module to call the text file, right?

        I appreciate your patience. I've been trying to work this out all day, and I know it should be obvious, but for some reason it isn't.
        Code:
        #!/usr/bin/python
        import sys
        print "script name is: ", sys.argv[0]
        print "first argument file name is: " , sys.argv[1]
        filename = sys.argv[1] #define the file name
        data = open( filename ) .read() #read everything in file into memory

        Comment

        • bartonc
          Recognized Expert Expert
          • Sep 2006
          • 6478

          #5
          Originally posted by TMS
          ok, so say my file name is file.txt (should it be formatted differently, like .py?). That is my arg, right? so:

          I appreciate your patience. I've been trying to work this out all day, and I know it should be obvious, but for some reason it isn't.
          Ok, let's go slowly here... The file with your python program in it (often called a "script") gets the .py extension for many reasons:
          1) This is the standard thing to do.
          2) IDLE will to automatic indentation and checking, colorizing and syntax checking.
          3) Windows will launch .py files using python (with no arguments).

          python myModule.py file.txt

          should call the module to call the text file, right?
          Here, the idea of "calling" file.txt isn't quite right. Python gets "called" with arguments. The first argument is the module to run and its name can be accessed by sys.argv[0]. Arguments coming after that are simply stored in sys.argv[1:] for the script to access as it needs. So, as ghostdog shows, if it is the name of a file, that file can be "opened" from within the script.
          That said, I'll modify my earlier program considering that sys.argv[0] is actually an argument to python and everthing after that (on the command line) is meant for your script.
          Code:
          # file: PyTest1.py
          import sys    # need to import the sys library module
          for arg in sys.argv[1:]    # a 'slice' prevents index errors
              print arg    # these will be all of the space-separated text on the command line
          raw_input("press any key")

          Comment

          • TMS
            New Member
            • Sep 2006
            • 119

            #6
            Originally posted by ghostdog74
            Code:
            #!/usr/bin/python
            import sys
            print "script name is: ", sys.argv[0]
            print "first argument file name is: " , sys.argv[1]
            filename = sys.argv[1] #define the file name
            data = open( filename ) .read() #read everything in file into memory

            this is so embarrassing... OK, I'm at the command line. I've got a module named myModule.py. In it I have a combination of the previous replies to my question and they are:

            Code:
            import sys
            
            for arg in sys.argv:
                print arg    
            
            print "script name is: ", sys.argv[0]
            print "first argument file name is: " , sys.argv[1]
            filename = sys.argv[1]
            data = open( filename ) .read()
            raw_input("press any key")    # a trick to keep the python console open
            I go to command line, type the following:

            python myModule.py someFile.txt
            I get the following:
            File "<stdin>", line 1
            python myModule.py.py

            SyntaxError: invalid syntax

            What am I doing wrong... I hate being such a noob.

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              Originally posted by TMS
              this is so embarrassing... OK, I'm at the command line. I've got a module named myModule.py. In it I have a combination of the previous replies to my question and they are:

              Code:
              import sys
              
              for arg in sys.argv:
                  print arg    
              
              print "script name is: ", sys.argv[0]
              print "first argument file name is: " , sys.argv[1]
              filename = sys.argv[1]
              data = open( filename ) .read()
              raw_input("press any key")    # a trick to keep the python console open
              I go to command line, type the following:

              python myModule.py someFile.txt
              I get the following:
              File "<stdin>", line 1
              python myModule.py.py

              SyntaxError: invalid syntax

              What am I doing wrong... I hate being such a noob.
              The problem is that you are in the Python sell, not a DOS command line.
              I'd also recommend that you proceed more slowly. For example, the code I gave doesn't require any error protection. The syntax anyList[1] will cause and error if there are less than two elements in the list. Python has cool ways of dealing with this, but you are not at this stage yet (but you will be very soon).

              Comment

              • dshimer
                Recognized Expert New Member
                • Dec 2006
                • 136

                #8
                Let me say right off that this isn't 100% relevant so should probably be ignored until the argv questions are worked out, but for future reference it seems a reasonable place to put it in.
                Originally coming from a C/C++ background I found that many programs I was re-writing wanted a reference to argc. I found it easiest to take the equivilent code and make one.

                Code:
                def argc():
                	'''
                	Should be the equivalent of the c style argc.
                	'''
                	return len(sys.argv)

                Comment

                • ghostdog74
                  Recognized Expert Contributor
                  • Apr 2006
                  • 511

                  #9
                  Originally posted by dshimer
                  Code:
                  def argc():
                  	'''
                  	Should be the equivalent of the c style argc.
                  	'''
                  	return len(sys.argv)
                  does the C++ argc mean the number of arguments? if it is, then the above
                  might be
                  Code:
                  return len(sys.argv[1:])
                  because sys.argv[0] is the script name.

                  Comment

                  • dshimer
                    Recognized Expert New Member
                    • Dec 2006
                    • 136

                    #10
                    Yeah, but if I remember right, like python, argv[0] is always the name of the command, so argc was always one off the number of actual argurments passed. So to keep things consistant in my mind, and in the ported code, I just kept the return value the same as it would have been.

                    There is no real reason to use this instead of the actual len command, it was just something I noticed early on, and mention for those coming from that background that are looking for argc or in this case the equivalent.

                    Originally posted by ghostdog74
                    does the C++ argc mean the number of arguments? if it is, then the above
                    might be
                    Code:
                    return len(sys.argv[1:])
                    because sys.argv[0] is the script name.

                    Comment

                    • TMS
                      New Member
                      • Sep 2006
                      • 119

                      #11
                      Ok, forgive my excitement, but... YEAH!!!! It works.

                      Thank you very much

                      Comment

                      • bartonc
                        Recognized Expert Expert
                        • Sep 2006
                        • 6478

                        #12
                        Originally posted by TMS
                        Ok, forgive my excitement, but... YEAH!!!! It works.

                        Thank you very much
                        ... YEAH!!!! It works... Believe me, we all share your exitement! Keep posting, Barton

                        Comment

                        Working...