带变量的Python中的Shell脚本

0 投票
3 回答
732 浏览
提问于 2025-04-16 21:47

我还是个Python新手。

我有一个文本文件,里面有一串数字,每个数字旁边还有两个“属性”。

250 121 6000.654
251 8472 650.15614
252 581  84.2

我想查找第一列的内容,然后把第二列和第三列的值分别存到不同的变量里,这样我就可以在后面使用它们。

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

这个方法可以打印出第二列的内容,但我想把这个输出赋值给一个变量,像这样(不过据我所知,这样会返回很多错误):

cmdOutput =  os.system(cmd)

另外,我还想根据一个变量来改变nawk的值,像这样:

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

如果有人能帮忙,感谢!

3 个回答

0

我觉得你想要的东西是:

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

首先,要格式化命令行字符串,可以使用

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

撰写回答