简体   繁体   English

python 中带有变量的 Shell 脚本

[英]Shell script in python with variables

Im still new to python.我对 python 还是新手。 I have a text file with a list of numbers, and each number has two 'attributes' along with it:我有一个带有数字列表的文本文件,每个数字都有两个“属性”:

250 121 6000.654
251 8472 650.15614
252 581  84.2

i want to search for the 1st column and return the 2nd and 3rd columns as separate variables so i can use them later.我想搜索第一列并将第二列和第三列作为单独的变量返回,以便我以后可以使用它们。

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

This works in that it prints the $2 column, but i want to assign this output to a variable, something like this (however this returns the number of errors AFAIK):这样做的原因是它打印了 $2 列,但我想将此 output 分配给一个变量,如下所示(但是这会返回错误的数量 AFAIK):

cmdOutput =  os.system(cmd)

also i would like to change the nawk'd value based on a variable, something like this:我也想根据一个变量更改 nawk 的值,如下所示:

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

If anyone can help, thanks.如果有人可以帮忙,谢谢。

Don't use cat and nawk .不要使用catnawk Please.请。

Just use Python只需使用 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]

No cat .没有cat No nawk .没有nawk

First of all, to format the cmd string, use首先,要格式化 cmd 字符串,使用

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

But really, you don't need an external command at all.但实际上,您根本不需要外部命令。

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)

I think what you're looking for is:我认为您正在寻找的是:

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

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

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