简体   繁体   English

Python - 如何为 subprocess.run sdterror 输出添加时间戳前缀?

[英]Python - How to prefix subprocess.run sdterror output with a time stamp?

I want to prefix the sdterror output from subprocess.run with a time stamp, unfortunately I have not been about to figure out how to do so.我想在 subprocess.run 的 sdterror 输出前面加上时间戳,不幸的是我还没有想出如何去做。

This part of my shell script runs FFMPEG and writes the output to a logfile :我的 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)

I have done a lot of research into this and I can't seem to find a solution, from what I have been reading the .run is the recommended approach for running subprocess.我对此进行了大量研究,但似乎找不到解决方案,从我阅读的内容来看,.run 是运行子进程的推荐方法。

I know how to create the time stamp:我知道如何创建时间戳:

str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))

Can someone explain how i would prefix the time stamp to each new line from the subprocess.run() call?有人可以解释我如何在 subprocess.run() 调用中为每个新行添加时间戳吗?

EDIT:编辑:

Just to be clear I want a timestamp at the start of each line, here is what I am getting using log为了清楚起见,我希望在每一行的开头有一个时间戳,这是我使用log得到的

Here is my logging code:这是我的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)

I think the issue is that conform_result.stderr is a string and I cannot append by lines, is this the case?我认为问题是conform_result.stderr是一个字符串,我不能按行附加,是这种情况吗?

BTW i am using python 3.5顺便说一句,我正在使用 python 3.5

You want to log each execution in a separate, timestamp-named file.您希望将每个执行记录在一个单独的、以时间戳命名的文件中。

First, notice that it's better to avoid : in file names.首先,请注意最好避免:在文件名中。 Windows cannot accept that, and you want portability. Windows 不能接受这一点,而您想要便携性。 So I changed the format.所以我改变了格式。

Basically, it's simple:基本上,这很简单:

  • compute the timestamp to capture start date计算时间戳以捕获开始日期
  • run the process运行进程
  • write the logfile with the timestamp in the name用名称中的时间戳写入日志文件

code:代码:

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))

这个https://docs.python.org/2/howto/logging-cookbook.html应该可以回答你的问题——它提到了来自不同进程、时间戳等的日志记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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