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?

0

1 Answer 1

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 ['.'])
Sign up to request clarification or add additional context in comments.

2 Comments

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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.