0

I'm trying to run my python script against specific folder when I specify the folder name in the terminal e.g

python script.py -'folder'

python script.py 'folder2'

'folder' being the I folder I would like to run the script in. Is there a command line switch that I must use?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Kam-ALIEN
  • 33
  • 1
  • 7

1 Answers1

1

The cd command in the shell switches your current directory.

Perhaps see also What exactly is current working directory?

If you would like your Python script to accept a directory argument, you'll have to implement the command-line processing yourself. In its simplest form, it might look something like

import sys

if len(sys.argv) == 1:
    mydir = '.'
else:
    mydir = sys.argv[1]

do_things_with(mydir)

Usually, you would probably wrap this in if __name__ == '__main__': etc and maybe accept more than one directory and loop over the arguments?

import sys
from os import scandir

def how_many_files(dirs):
    """
    Show the number of files in each directory in dirs
    """
    for adir in dirs:
        try:
            files = list(scandir(adir))
        except (PermissionError, FileNotFoundError) as exc:
            print('%s: %s' % (adir, exc), file=sys.stderr)
            continue
        print('%s: %i directory entries' % (adir, len(files)))

if __name__ == '__main__':
    how_many_files(sys.argv[1:] or ['.'])
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks for your reply. But what I want to do is run my script against the sub-directory I specify..So if I want to the script to run inside folder2 I would just put $python script.py folder2 – Kam-ALIEN Jun 10 '21 at 03:49
  • The second half of this answer explains exactly how to do this. If `script.py` should accept a command-line argument, it will need to pick it up from `sys.argv`. Of course, there are third-party libraries which help with this if you don't want to do it yourself, but without additional requirements, it's hard to recommend anything in particular. – tripleee Jun 10 '21 at 03:52