Search code examples
pythonpython-3.xhierarchyargparsesys

Argparse: what is the difference between "sys.argv[1]" and "args.input"?


I'm learning how to use argparse and it's a labyrinth for me.

I have a code that works: if I run python Test.py . it prints all files in hierarchy using this code

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import argparse
import sys
import glob

#parser = argparse.ArgumentParser()                             
#parser.add_argument('-input', dest='input',help="input one or more files",nargs='+',metavar=None                           
#args = parser.parse_args()

def dirlist(path, c = 1):

        for i in glob.glob(os.path.join(path, "*")):
                if os.path.isfile(i):
                        filepath, filename = os.path.split(i)
                        print ('----' *c + filename)

                elif os.path.isdir(i):
                        dirname = os.path.basename(i)
                        print ('----' *c + dirname)
                        c+=1
                        dirlist(i,c)
                        c-=1


#path = os.path.normpath(args.input)
path = os.path.normpath(sys.argv[1])
print(os.path.basename(path))
dirlist(path)

But, as I want to understand how argparse works I want to run the code using python Test.py - input .

But nothing works.

I know I'm close, I have written a sort of Frankenstein code which is commented.

Where am I wrong? I feel I'm so close to the solution...


Solution

  • Thank you @match for the right tips. Problem was I was using nargs='+' in the argparse definition

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import os
    import argparse
    import sys
    import glob
    
    parser = argparse.ArgumentParser()                              
    parser.add_argument('-input', dest='input',help="input one or more files",metavar=None)                     
    args = parser.parse_args()
    
    def dirlist(path, c = 1):
    
            for i in glob.glob(os.path.join(path, "*")):
                    if os.path.isfile(i):
                            filepath, filename = os.path.split(i)
                            print ('----' *c + filename)
    
                    elif os.path.isdir(i):
                            dirname = os.path.basename(i)
                            print ('----' *c + dirname)
                            c+=1
                            dirlist(i,c)
                            c-=1
    
    
    path = os.path.normpath(args.input)
    print(os.path.basename(path))
    dirlist(path)
    

    The code works now!