Napster
Napster

Reputation: 99

Passing custom date/time inside bash command running in Python3

I am trying to run a python program/package with some custom bash command inside py3. Rest of the pure python code is working but this bash command is giving me lot of pain in getting an output files. Currently, I am using this command inside Python 3 (py file)

import os
os.system("now=$(date +%Y-%m-%d)")
os.system("-d biden_${now}.txt --function=linear -f trump_${now}.txt")
os.system("-i trump_${now}.txt --daemon --quiet --port 8022")

but in output directory I must get files with names like

biden_2021-01-03.txt and trump_2021-01-03.txt

which must includes today's date. When I am trying to do this via fix file names, it performs the required operations of python program/package but when I am trying to make it customise based on date wise file operations, it is just giving me files with names:

biden_.txt and trump_.txt

but with no dates in it. Can someone please guide me where I am doing wrong or any easier solution to achieve this? I am running this on/using Python 3.5.3, Debian GNU/Linux 9 Operating system, Kernel: Linux 4.9.0-9-amd64, Architecture: x86-64.

Upvotes: 0

Views: 825

Answers (3)

Peter Novotny
Peter Novotny

Reputation: 63

The os.system calls are spawning in new shell. See samples

Sample1:

os.system("now=$(date +%Y-%m-%d)")
os.system("echo $now")

Sample2:

os.system("now=$(date +%Y-%m-%d); echo $now")
2021-01-03

You can combine into something like

os.system("echo \"Your file name is biden`date +%Y-%m-%d`.txt\"")
Your file name is biden2021-01-03.txt

But your time will slowly shift, depending how long your processing will take.

If you do not want your time to drift, but to match your start time, use python date as in meantime posted by abc

Upvotes: 1

Maurice Lam
Maurice Lam

Reputation: 1794

os.system creates a new subshell for each call, so the now env variable is not available in the subsequent calls.

You can either directly generate the date string in Python and pass it as a format string:

now = datetime.datetime.now().date().isoformat()
os.system("-d biden_{now}.txt --function=linear -f trump_{now}.txt".format(now=now))
os.system("-i trump_{now}.txt --daemon --quiet --port 8022".format(now=now))

Or you can put the now variable in Python's environment and reference it inside the os.system call:

os.environ['now'] = datetime.datetime.now().date().isoformat()
os.system("-d biden_${now}.txt --function=linear -f trump_${now}.txt")
os.system("-i trump_${now}.txt --daemon --quiet --port 8022")

Upvotes: 2

abc
abc

Reputation: 11949

If this is just for the filenames you could achieve it with the datetime module.

>>> from datetime import datetime
>>> today_date = datetime.today().strftime('%Y-%m-%d')
>>> cmd = f"-d biden_{today_date}.txt --function=linear -f trump_{today_date}.txt"
>>> cmd
'-d biden_2021-01-03.txt --function=linear -f trump_2021-01-03.txt'

Upvotes: 3

Related Questions