我想在subprocess.run的输出结果前加上一个时间戳,不幸的是我还没想好怎么做。
我的shell脚本的这一部分运行FFMPEG并将输出写入日志文件:
try:
conform_result = subprocess.run(ffmpeg_conform, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(conform_result.stderr)
c_log = open(config.transcode_logs + 'c_' + task_id + '_detail.txt', 'w')
c_log.write(conform_result.stderr)
c_log.close()
except Exception as e:
print('task ' + task_id + ' has failed for the following reason: ' + e)我对此做了很多研究,但我似乎找不到一个解决方案,从我所做的事情来看,.run是运行子进程的推荐方法。
我知道如何创建时间戳:
str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))有人能解释一下如何在subprocess.run()调用中的每个新行加上时间戳吗?
编辑:
为了清楚起见,我想在每行的开头加上一个时间戳,下面是我使用log得到的时间戳
下面是我的logging代码:
file_log = logging.getLogger()
file_log.setLevel(logging.DEBUG)
fh = logging.FileHandler(filename=task_log + 'task_' + task_id + '.txt')
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
file_log.addHandler(fh)
# Conform section.
ffmpeg_conform_cmd, seg_number = functions.parse_xml(core_metadata_path, processing_temp_conform, base_mp4)
ffmpeg_conform = str(ffmpeg_conform_cmd).replace('INPUT_FILE', conform_source)
print(timestamp() + ': ' + ffmpeg_conform)
logging.info(ffmpeg_conform)
# Updated database stating that the conform process has started
sql_conform = "UPDATE task SET status ='Conforming' WHERE task_id ='" + task_id + "'"
cursor.execute(sql_conform)
dbc.commit()
try:
conform_result = subprocess.run(ffmpeg_conform, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(timestamp() + ': ' +conform_result.stderr)
file_log.info(conform_result.stderr)
except Exception as e:
print(timestamp() + ': Conform has Failed: ' + task_id)
print(e)
file_log.error('Conform has Failed: ' + task_id)
file_log.error(e)我认为问题是conform_result.stderr是一个字符串,我不能逐行追加,是这样吗?
顺便说一句,我使用的是python 3.5
发布于 2017-01-27 01:40:45
您希望在一个单独的、以时间戳命名的文件中记录每次执行。
首先,请注意在文件名中最好避免使用:。Windows不能接受这一点,而您需要可移植性。所以我改变了格式。
基本上,它很简单:
代码:
try:
timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d_%H_%M_%S")
conform_result = subprocess.run(ffmpeg_conform, stdout=PIPE, stderr=PIPE, universal_newlines=True)
log_file = os.path.join(config.transcode_logs,"c_{}_{}_detail.txt".format(timestamp,task_id))
with open(log_file,"w") as c_log:
c_log.write(conform_result.stderr)
except Exception as e:
print('task {} has failed for the following reason: {}'.format(task_id,e))发布于 2017-01-27 05:44:23
这个,https://docs.python.org/2/howto/logging-cookbook.html,应该可以回答你的问题--它提到了来自不同进程的日志,时间戳等等。
https://stackoverflow.com/questions/41809597
复制相似问题