A
A
Alexander Bureyko2021-11-06 16:34:02
Python
Alexander Bureyko, 2021-11-06 16:34:02

How to add the ability to pass other files and directories to the code directly on the command line?

I'm learning python from the book Byte of Python and I'm a little confused about how to implement the following task:

Another possible improvement would be the ability to pass other files and directories to the script directly on the command line. These names can be obtained from the sys.argv list and added to our source list using the list class's extend method.

and here is my code:

import os, time as t

# Файлы и каталоги, которые необходимо скопировать, собираются в список.

source = ['"C:\\my documents"']

# Резервные копии должны храниться в основном каталоге резерва.

target_dir = 'D:\\backup'

today = os.path.join(target_dir, t.strftime('%Y%m%d'))

if not os.path.exists(today):
    os.mkdir(today) # создание каталога, если он отсутствует
    print('Каталог успешно создан', today)

now = t.strftime('%H%M%S.zip')

comment = input('Введите имя zip архива --> ')

if len(comment) == 0: # Если пользователь ничего не ввел, то имя zip архива - now
    target = os.path.join(today, now)
else:
    target = os.path.join(today, comment.replace(' ', '_') + '.zip')

# Используем команду "zip" для помещения файлов в zip-архив:

zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))

# Запускаем создание резервной копии:

if os.system(zip_command) == 0:
    print('Резервная копия успешно создана в', target)
else:
    print('Создание резервной копии НЕ УДАЛОСЬ')

Extended answers are appreciated. Many thanks to all who answered!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-06
@alexander1212

"Another possible improvement would be the ability to pass other files and directories to the script right on the command line. These names can be obtained from the sys.argv list and added to our source list using the list class's extend method."
Allotment is mine.
In general, sys.argv stores a list of command line options. 0th always contains the path and name of the executable script, but the subsequent ones are set by the user.
In simple cases, you can just work with sys.argv as a list, but if you have something more complex (like optional arguments), then look towards argparse .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question