cat、grep 和 cut - 翻译成 Python
可能已经有很多人问过这个问题或者给出了解决方案,但我还是忍不住想问一下:我在一个bash脚本中使用了以下命令:
var=$(cat "$filename" | grep "something" | cut -d'"' -f2)
现在,由于一些问题,我需要把所有代码转换成Python。我之前从来没用过Python,完全不知道怎么用Python实现这些命令的功能。有没有人能给我一些建议,怎么用Python来解决这个问题呢?
5 个回答
3
你需要对文件的每一行进行循环处理,这样你就得了解一下字符串方法。
with open(filename,'r') as f:
for line in f.readlines():
# python can do regexes, but this is for s fixed string only
if "something" in line:
idx1 = line.find('"')
idx2 = line.find('"', idx1+1)
field = line[idx1+1:idx2-1]
print(field)
另外,你还需要一种方法来把文件名传递给你的Python程序,顺便说一下,也许你还想传递一个要搜索的字符串……
以后如果能的话,尽量问一些更具体的问题。
5
你需要使用 os.system
模块来执行命令行指令。
import os
os.system('command')
如果你想把输出结果保存起来以便以后使用,就需要用到 subprocess
模块。
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
10
在Python中,如果不使用外部库,代码大概是这样的(未经测试):
with open("filename") as origin:
for line in origin:
if not "something" in line:
continue
try:
print line.split('"')[1]
except IndexError:
print
105
你需要对Python语言和它的标准库有更好的理解,才能理解这个表达式。
cat "$filename":这个命令会读取文件cat "$filename"
的内容,并把内容输出到屏幕上。
|
:这个符号叫做管道,它的作用是把前一个命令的输出(也就是屏幕上显示的内容)传递给下一个命令作为输入。
grep "something":这个命令会在指定的文本文件中(如果有的话)或者在输入的数据中搜索something
这个模式,并返回匹配的行。
cut -d'"' -f2:这个命令会用特定的分隔符来拆分字符串,并从结果中提取特定的字段。
Python中的等价写法
cat "$filename" | with open("$filename",'r') as fin: | Read the file Sequentially
| for line in fin: |
-----------------------------------------------------------------------------------
grep 'something' | import re | The python version returns
| line = re.findall(r'something', line)[0] | a list of matches. We are only
| | interested in the zero group
-----------------------------------------------------------------------------------
cut -d'"' -f2 | line = line.split('"')[1] | Splits the string and selects
| | the second field (which is
| | index 1 in python)
组合
import re
with open("filename") as origin_file:
for line in origin_file:
line = re.findall(r'something', line)
if line:
line = line[0].split('"')[1]
print line