I have requirement to copy files from source to destination in python file. used
distutils.dir_util.copy_tree(src_dir,dest1_dir);
distutils.dir_util.copy_tree(src_dir,dest2_dir);
src_dir
, dest1_dir
and dest2_dir
are hard coded in the python file as
src_dir =/xx/ttt/yyy
dest1_dir=/xx/yyy/uuuu
But don't want hard code. I am calling this python script from abc.bat file
how to pass src_dir
, dest1_dir
, dest2_dir
to python script from bat file and in python script how to get the passed parameters from the bat script. so that I replace the src and destination directory in the copy tree.
If you want to do something fast @AdamSmith's approach will be great.
On the other hand, if your program will grow a lot on options or you want to create more elegant parameters such as:
your_script --src-dir= src_dir --dest-dir= dest_dir
you can use argparse which will do the job great.
Even more, if you want to print something like this:
$ python copier.py -h
usage: copier.py [-h] [--src-dir] [--dest-dir]
Copies a directory from source to destination
positional arguments:
--src-dir The source directory
--dest-dir The destination directory
optional arguments:
-h, --help show this help message and exit
You can access the whole argument values list with
import sys
sys.argv
the first element is always the name of the file, so you're looking at sys.argv[1:]
src, dst = sys.argv[1:]
But is there some reason that you're using the distutils
module for this? It's more often called from shutil
import shutil
import sys
src, dst = sys.argv[1:]
try:
shutil.copytree(src, dst)
# shutil.copytree(src, dst2) # how are you generating dst2?
except Exception:
# something went wrong. Unless there's a reasonable way to recover we should just
raise
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.