dnc*_*dnc 34 python linux bash grep cut
也许有足够的问题和/或解决方案,但我无法帮助自己解决这个问题:我在bash脚本中使用了以下命令:
var=$(cat "$filename" | grep "something" | cut -d'"' -f2)
Run Code Online (Sandbox Code Playgroud)
现在,由于一些问题,我必须将所有代码转换为python.我之前从未使用过python,我完全不知道如何处理postet命令.任何想法如何用python解决?
Abh*_*jit 72
您需要更好地理解python语言及其标准库来翻译表达式
cat"$ filename":读取文件cat "$filename"并将内容转储到stdout
|:pipe重定向上stdout一个命令并将其提供给stdin下一个命令
grep"something":搜索正则表达式something纯文本数据文件(如果指定)或在stdin中搜索匹配的行.
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)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
在Python中,没有外部依赖,它就像这样(未经测试):
with open("filename") as origin:
for line in origin:
if not "something" in line:
continue
try:
print line.split('"')[1]
except IndexError:
print
Run Code Online (Sandbox Code Playgroud)
你需要使用os.system模块来执行shell命令
import os
os.system('command')
Run Code Online (Sandbox Code Playgroud)
如果要保存输出以供以后使用,则需要使用subprocess模块
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
Run Code Online (Sandbox Code Playgroud)