[英]How to evaluate a python variable and pass it as a argument to a command
在下面的python脚本中,我试图将当前日期和时间戳记转换为名为logfile的python变量,该变量作为参数传递给使用os.system(...)
执行的Windows命令的输出重定向
但是我无法传递变量日志文件。 执行完此脚本后,我希望看到一个文件:例如log_28052019_133838.txt,其名称在执行时具有日期和时间戳,并且具有dir / od命令的输出,但是存储在文件logfile中,告诉我说,在作为输出重定向文件名传递之前,未对变量名logfile的python表达式求值。
有人可以指出我,我想念的是什么,实现我想要做的正确方法是什么。
#!/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)
似乎logfile
的值将允许您使用字符串格式来定义命令(尽管此命令很脆弱,在实践中不应使用):
logfile = time.strftime("log_%d%b%Y_%H%M%S.txt")
rcmd = 'dir /OD > {}'.format(logfile)
os.system(rcmd)
不过,使用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.