2011-07-18 72 views
0

我还是python的新手。 我有编号列表的文本文件,每个数字有两个“属性”与它一起:python中的shell脚本变量

250 121 6000.654 
251 8472 650.15614 
252 581 84.2 

我要搜索的第一列,并返回第二和第三列作为独立变量,以便我可以稍后使用它们。

cmd = """ cat new.txt | nawk '/'251'/{print $2}' """ 
os.system(cmd) 

这工作,因为它打印$ 2栏,但我想转让本输出到一个变量,像这样(但是这个据我所知返回错误的号码):

cmdOutput = os.system(cmd) 

也我想根据变量更改nawk'd值,如下所示:

cmd = """ cat new.txt | nawk '/'$input'/{print $2}' """ 

如果有人能帮忙,谢谢。

+0

你见过http://stackoverflow.com/questions/6736627/python-command-execution-output/6736689#6736689 – Dirk

+0

你可以给我们的输出,就像它是什么打印? – TheChes44

+0

为什么你想要使用awk,何时可以轻松使用纯Python? – utdemir

回答

5

请勿使用catnawk。请。

只需使用Python

import sys 
target= raw_input('target: ') # or target= sys.argv[1] 
with open('new.txt','r') as source: 
    for columns in (raw.strip().split() for raw in source): 
     if column[0] == target: print column[1] 

没有cat。否nawk

+1

谢谢你让我在正确的道路上肯定。对不起使用awk,菜鸟错误! – Kilizo

+0

@Kilizo:你有Python。你不需要太多。你几乎不需要壳。 –

0

我想你要找的是什么:

subprocess.Popen(["cat", "new.txt","|","nawk","'/'$input/{print $2}'"], stdout=subprocess.PIPE).stdout 
2

首先,格式化字符串CMD,使用

input = '251' 
cmd = """ cat new.txt | nawk '/'{input}'/{{print $2}}' """.format(input=input) 

但实际上,你并不需要一个外部命令在所有。

input = '251' 
with open('new.txt', 'r') as f: 
    for line in file: 
     lst = line.split() 
     if lst[0] == input: 
      column2, column3 = int(lst[1]), float(lst[2]) 
      break 
    else: # the input wasn't found 
     column2, column3 = None, None 
print(column2, column3)