R
R
Roman2017-02-03 11:38:43
Python
Roman, 2017-02-03 11:38:43

How to insert a variable into os.system?

Good day. Tell me how to correctly insert a variable into the os.system command.
The script makes a monthly archive of backups and cleans the directory with backups. I get the feeling that this is not the prettiest solution. I had to introduce an extra variable arch_name in order to insert the month number into the archive name. The script is executed on the first day of the month, so you have to subtract one from the ordinal number of months.

import os
import datetime
now_date = datetime.date.today()
month = now_date.month
if int(month) - 1 != 0: #Проверка янв или нет
    t = int(month) - 1
else:
    t = 12
os.chdir('/backup')
arch_name = ('tar cvf /backup_month/' + str(t) + '.tar.gz * && rm *')
os.system(arch_name)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-02-03
@rnqlover

[12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Do you need such numbering of months? Then here's the one-liner:

os.system("tar cvf backup/backup_month/%d.tar.gz * && rm backup/*" % ((datetime.date.today().month - 2) % 12 + 1))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question