简体   繁体   English

使用python子进程执行awk命令

[英]executing awk command using python subprocess

I am trying to extract year field from "date" output Code: 我试图从“日期”输出代码中提取年份字段:

import sys
import os
import subprocess
per_name = input('Enter name:')
age = input('Enter age:')
to_date = subprocess.Popen(["date"],stdout=subprocess.PIPE)
date = subprocess.Popen(['awk',"'{print","$NF}'"],stdin=to_date.stdout)
act_date = date.communicate()
to_date=str(act_date)
print("Year: "+act_date)

I am getting following error: 我收到以下错误:

awk: syntax error at source line 1
context is
 >>> ' <<< 
missing }
awk: bailing out at source line 1
Traceback (most recent call last):
File "pyt_ex1.py", line 10, in <module>
print("Year: "+act_date)

Please help me with right way of extracting it using 'awk' 请帮助我使用'awk'以正确的方式提取它

Why are you trying to use awk for this? 你为什么要尝试使用awk呢? python's str.split() will split the input by spaces, doing the same thing as awk. python的str.split()将按空格分割输入,与awk做同样的事情。

year = date_string.split()[-1]

You can then just get the last element of the list. 然后,您可以只获取列表的最后一个元素。 In fact you don't even need to get the date from bash either. 事实上,你甚至不需要从bash获取日期。 Python has time and datetime modules. Python有时间和日期时间模块。 It would look like this: 它看起来像这样:

import datetime
year = datetime.date.today().year

In the event that you do want to use awk and not some other mechanism this will work (note the removed quotation marks in the second argument): 如果你确实想要使用awk而不是其他一些机制,那么这将起作用(请注意第二个参数中删除的引号):

date = subprocess.Popen(["awk","{print $NF}"],stdin=to_date.stdout)

Tested this on OSX and Fedora. 在OSX和Fedora上测试过。

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

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