我正在尝试编写一个脚本,使用Python中的Linux命令将以下输出到文件夹(YYYYMMDDHHMMSS =当前日期和时间),ID在配置文件中
1234_YYYYMMDDHHMMSS.txt
12345_YYYYMMDDHHMMSS.txt
12346_YYYYMMDDHHMMSS.txt
我有一个包含ID列表的配置文件
id1 = 1234
id2 = 12345
id3 = 123456
我希望能够在python中循环这些并将它们合并到linux命令中。
目前,我的linux命令在python中是硬编码的
import subprocess
import datetime
now = datetime.datetime.now()
subprocess.call('autorep -J 1234* -q > /home/test/output/1234.txt', shell=True)
subprocess.call('autorep -J 12345* -q > /home/test/output/12345.txt', shell=True)
subprocess.call('autorep -J 123456* -q > /home/test/output/123456.txt', shell=True)
print now.strftime("%Y%m%d%H%M%S")
日期时间是定义的,但当前没有做任何事情,除非将它打印到控制台,当我想将它合并到输出txt文件中时。但是,我希望能够写一个循环来做这样的事情
subprocess.call('autorep -J id1* -q > /home/test/output/123456._now.strftime("%Y%m%d%H%M%S").txt', shell=True)
subprocess.call('autorep -J id2* -q > /home/test/output/123456._now.strftime("%Y%m%d%H%M%S").txt', shell=True)
subprocess.call('autorep -J id3* -q > /home/test/output/123456._now.strftime("%Y%m%d%H%M%S").txt', shell=True)
我知道我需要使用ConfigParser,目前已编写了这篇文章,只是将配置文件中的ID打印到控制台。
from ConfigParser import SafeConfigParser
import os
parser = SafeConfigParser()
parser.read("/home/test/input/ReportConfig.txt")
def getSystemID():
for section_name in parser.sections():
print
for key, value in parser.items(section_name):
print '%s = %s' % (key,value)
print
getSystemID()
但正如帖子的开头所提到的,我的目标是能够遍历ID,并将它们合并到我的linux命令中,同时将日期时间格式添加到文件的末尾。我想我需要的是上面函数中的某种while循环,以获得我想要的输出类型。但是,我不确定如何将ID和日期时间调用到linux命令中。
答案 0 :(得分:1)
到目前为止,你有大部分需要的东西,你只是缺少一些东西。
首先,我认为使用ConfigParser对此有点过分。但它很简单,所以让我们继续吧。让我们将getSystemID
更改为返回ID的生成器,而不是将其打印出来,只需更改一行。
parser = SafeConfigParser()
parser.read('mycfg.txt')
def getSystemID():
for section_name in parser.sections():
for key, value in parser.items(section_name):
yield key, value
使用生成器,我们可以直接在循环中使用getSystemID
,现在我们需要将其传递给子进程调用。
# This is the string of the current time, what we add to the filename
now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# Notice we can iterate over ids / idnumbers directly
for name, number in getSystemID():
print name, number
现在我们需要构建子进程调用。上面的大部分问题都是知道如何格式化字符串,语法描述为here。
我还将就如何使用subprocess.call
做两点说明。首先,传递一个参数列表而不是一个长字符串。这有助于python知道引用的参数,因此您不必担心它。您可以在subprocess和shlex文档中阅读相关内容。
其次,您使用命令中的>
重定向输出,并且(如您所见)需要shell=True
才能使用此功能。 Python可以为您重定向,您应该使用它。
在拾取环路中拾取我上面的位置。
for name, number in getSystemID():
# Make the filename to write to
outfile = '/home/test/output/{0}_{1}.txt'.format(number, now)
# open the file for writing
with open(outfile, 'w') as f:
# notice the arguments are in a list
# stdout=f redirects output to the file f named outfile
subprocess.call(['autorep', '-J', name + '*', '-q'], stdout=f)
答案 1 :(得分:0)
您可以使用Python的format
指令插入日期时间。
例如,您可以使用1234
前缀和datime标记创建一个新文件,如下所示:
new_file = open("123456.{0}".format(datetime.datetime.now()), 'w+')
我不确定我是否明白你在寻找什么,但我希望这会有所帮助。