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.
3
Answers
If this is just for the filenames you could achieve it with the
datetime
module.os.system
creates a new subshell for each call, so thenow
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:
Or you can put the
now
variable in Python’s environment and reference it inside theos.system
call:The os.system calls are spawning in new shell. See samples
Sample1:
Sample2:
You can combine into something like
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