I'm trying to run my python script against specific folder when I specify the folder name in the terminal eg
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?
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 ['.'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.