[英]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(...)
在下面的python脚本中,我试图将当前日期和时间戳记转换为名为logfile的python变量,该变量作为参数传递给使用os.system(...)
执行的Windows命令的输出重定向
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. 执行完此脚本后,我希望看到一个文件:例如log_28052019_133838.txt,其名称在执行时具有日期和时间戳,并且具有dir / od命令的输出,但是存储在文件logfile中,告诉我说,在作为输出重定向文件名传递之前,未对变量名logfile的python表达式求值。
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
的值将允许您使用字符串格式来定义命令(尽管此命令很脆弱,在实践中不应使用):
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. 不过,使用subprocess
模块会更安全,以避免出现任何外壳问题。
logfile = time.strftime("log_%d%b%Y_%H%M%S.txt")
with open(logfile, "w") as fh:
subprocess.run(['dir', '/OD'], stdout=fh)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.