【问题标题】:how to remove unnecessary chars from date command output in python如何从python中的日期命令输出中删除不必要的字符
【发布时间】:2013-05-08 07:54:56
【问题描述】:

我是 python 新手。如果它太简单,请原谅我。我只想在 python 中使用date 命令提取日期

import subprocess

p = subprocess.Popen(["date", '+%m/%d/%y'], stdout=subprocess.PIPE)

output,err = p.communicate()

print (output)

现在正在打印

b'05/14/13\n'

如何在开始时删除不必要的 '\n' 和 b

【问题讨论】:

  • 您是否考虑过使用 import datetime print datetime.date.today().strftime('%m/%d/%y') ?只是说...
  • @tink:在这种情况下,使用datetime 而不是time 有什么特别的价值吗?它似乎更复杂。
  • @tink 谢谢。为我工作。
  • @tink 我怎样才能在时间上达到同样的效果。我正在尝试 datetime.time.strftime('+%H:%M:%S')
  • 我使用了datetime.datetime.now().strftime('%H:%M:%S')

标签: python linux shell command


【解决方案1】:

Thomas 的回答是正确的,但我觉得需要更多解释。

我总是 .decode('utf8') p.communicate()check_output() 等的结果。这是因为 stdout/stdin 始终以二进制模式打开,除非您明确提供文件句柄,因此您始终接收/发送 bytes,而不是 str em>。

在这种情况下,我建议只使用 check_output(['date','+%m/%d/%y']) 而不是创建一个 Popen 对象,然后您基本上将其丢弃:)

所以,我建议将其重写为:

import subprocess
result = subprocess.check_output(['date', '+%m/%d/%y']).decode('utf8').rstrip()
print (result)

在更元的层面上,有一个问题是您是否甚至需要使用subprocess 来执行此任务。 毕竟,有time.strftime() 用于格式化日期/时间。这个:

import time
print(time.strftime('%m/%d/%y'))

以更简单的方式实现整个程序的预期效果。

同样来自tink的评论:

 import datetime 
 print datetime.date.today().strftime('%m/%d/%y') 

【讨论】:

  • 谢谢。我会参考这个以供将来使用。我用过 strftime 函数
【解决方案2】:

b表示是二进制字符串,可以通过output.decode('ascii')得到一个unicode字符串。要摆脱尾随的换行符:

output = output.strip()
output = output.decode('ascii')
print(output)

【讨论】:

  • 谢谢。我会参考这个以供将来使用
【解决方案3】:
>>> str(b'05/14/13\n').rstrip()
'05/14/13'

速度比较:

>>> import timeit
>>> timeit.timeit(r"b'05/14/13\n'.decode('ascii').rstrip()")
0.7801015276403488
>>> timeit.timeit(r"str(b'05/14/13\n').rstrip()")
0.2503617235778428

【讨论】:

  • 当我看到一个空的str(some_bytes_object) 时,我的脑海中总会有一个问题——使用的是什么编码? (“系统默认编码”,又名sys.getdefaultencoding()?)。
  • 出于好奇,这里还有一些数字:在我的系统上,从冷启动开始,..decode(..)..rstrip() 需要 1.36967,str(..).rstrip() 需要 1.15654,而我自己喜欢的选项 str(..,'utf8').rstrip() 需要 1.33954 - - 有趣的是,显式指定编码参数会慢多少。
  • @kampu 这很有趣(感谢运行这些测试)。我最喜欢你最喜欢的可读性,但如果性能是一个问题,str(...).rstrip() 似乎是最好的
  • 谢谢。我将在未来使用它。
猜你喜欢
  • 2018-11-17
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
  • 2017-03-01
相关资源
最近更新 更多