简体   繁体   中英

How to evaluate a python variable and pass it as a argument to a command

In a python script below, I am trying to get current date and time stamp into a python variable named logfile which is passed as argument to output redirection of a windows command which is executed using os.system(...)

But I am unable to pass the variable logfile. After executing this script, I am hoping to see a file: eg log_28052019_133838.txt whose name has date and timestamp at time it is executed, and which has output of the dir /od command, but instead it is stored in file logfile, telling me that python expression for variable name logfile is not getting evaluated before passing as output redirection file name.

Can someone point me, what am i missing and what would be the correct way to achieve what I am looking to do.

#!/bin/python

import os
import time

fstr = time.strftime("%d%b%Y_%H%M%S")
logfile = "log_"+fstr+".txt"
rcmd = 'dir /OD >logfile '

os.system(rcmd)

It appears that the value of logfile would allow you to use string formatting to define the command (though this is fragile and should not be used in practice):

logfile = time.strftime("log_%d%b%Y_%H%M%S.txt")
rcmd = 'dir /OD > {}'.format(logfile)
os.system(rcmd)

It would be safer to use the subprocess module, though, to avoid any shell issues.

logfile = time.strftime("log_%d%b%Y_%H%M%S.txt")
with open(logfile, "w") as fh:
    subprocess.run(['dir', '/OD'], stdout=fh)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM