簡體   English   中英

在Python中處理標准輸入並重定向到標准輸出

[英]Manipulating stdin and redirect to stdout in Python

我正在嘗試編寫一個簡單的python腳本,其中

  1. 它從標准輸入取值
  2. 替換特定的匹配詞
  3. 將具有新值的輸出傳遞回stdout

我只有一部分從stdin中獲取值並尋找匹配的單詞,在那之后我有點卡住了。

import re
import sys

for line in sys.stdin:
    matchObj = re.search(r'<something>(.*)</something>',line)
    if matchObj:
        oldWord = matchObj.group(1)
        print oldWord

foo的內容

<something>REPLACEME</something>
<blah>UNTOUCH</blah>

理想情況下,如果我運行此命令

cat foo | ./test.py

我會得到這樣的東西

<something>NEWWORD</something
<blah>UNTOUCH</blah>

您在尋找re.sub嗎?

import re
import sys

for line in sys.stdin:
    sys.stdout.write(re.sub(r'(<something>)REPLACEME(</something>)',
                            r'\1NEWWORD\2',
                            line))

在示例數據上運行以上代碼:

$ echo '<something>REPLACEME</something>\n<something>UNTOUCH</something>' | python2 test.py
<something>NEWWORD</something>
<blah>UNTOUCH</blah>

請注意,使用正則表達式解析XML可能不是一個好主意。 Python標准庫帶有許多XML模塊

這是一個例子:

import sys
import xml.etree.ElementTree

tree = xml.etree.ElementTree.parse(sys.stdin)
root = tree.getroot()

for node in root.iter('something'):
    if node.text == 'REPLACEME':
        node.text == 'NEWWORD'

tree.write(sys.stdout)

上面的工作原理是一樣的:

$ echo '<root><something>REPLACEME</something>\n<blah>UNTOUCH</blah></root>' | python2 test.py
<root><something>REPLACEME</something>
<blah>UNTOUCH</blah></root>

如果您運行cat foo | ./test.py則將cat foo | ./test.py cat foo | ./test.pytest.py: command not found ,您需要運行以下命令: cat foo |python ./test.py

那么您的代碼輸出將是:

REPLACEME

但是對於所需的輸出,您需要使用re.sub()

import re
import sys

for line in sys.stdin:
    matchObj = re.sub(r'<something>(.*)</something>','<something>NEWWORD</something>',line)
    if matchObj:
        print matchObj

輸出:

<something>NEWWORD</something>

<blah>UNTOUCH</blah>

另外,作為Python方式,您可以使用ElementTree XML API

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM