[英]Can we use a variable containing linux command result in the python code
[英]How can we implement the Linux command `sed` in python?
sed
是什么? 如果您已經知道sed
是什么,您可以跳過閱讀本文的下一部分。
sed
命令的示例是什么?
假設:
input.txt
的文件中讀取數據input.txt
包含大量英文文本(例如 Jane Austin 小說)"dog"
替換每次出現的字符串“ cat
”input.txt
保持不變,並將 output 寫入當前工作目錄中名為output.txt
的文件執行上述操作的sed
命令如下所示:
sed 's/cat/dog/g' input.txt | tee output.txt
sed
命令的非常籠統的描述,沒有示例
更流行的 Linux 命令之一被命名為sed
“ sed ”代表“ stream 編輯器”
sed
具有以下屬性:
sed
機器(例如“hello world”)sed
修改它收到的文本。sed
將修改文本發送到 output 字符的 stream。output stream 通常是 ASCII 編碼的文本文件)
sed
主要使用正則表達式來識別文本模式,並將其替換為其他文本。
我們想在 python 中實現sed
。
但是,我們的sed
實現應該可以在運行不同於 Linux 的操作系統的計算機上運行。
以下是不可接受的:
import subprocess
cmd = "sed 's/cat/dog/g' input.txt | tee output.txt".split(" ")
subprocess.call(cmd)
sed
時的悲傷嘗試一個嘗試的解決方案如下所示。
import subprocess
import os
import sys
def sed(stryng, istream=None, ostream=None):
if sys.platform == "linux":
subprocess.run(["sed", stryng])
subprocess.call(['sed', 's/\"//g', inp], stdout=out_file)
elif os.name == 'nt':
# if running Windows
lead_up = "@ powershell - Command get-content somefile.txt | %{{$_ -replace "
expression = ""
replacement = ""
subprocess.run(lead_up + f"\"\"{expression}\",\"{replacement}\"}}")
else:
raise NotImplementedError()
用法:
in_file = open("report_new.txt", "r")
out_file = open("report_new.txt", "w")
sed("'s/Nick/John/g'", in_file, out_file)
out_file.close()
in_file.close()
如果您無論如何都在使用 Python,那么您不妨直接操作該文件。 (另見https://askubuntu.com/a/747455 )偽代碼:
subject, replacement = split pattern at /
s = read in_file
in s replace each subject with replacement
write s to out_file
我不熟悉sed
如何解釋模式的細節; 由於從 sed 的 Regex 方言切換到 Python 方言,可能會出現一些意外行為。 但是,基本功能應該大致相同。 但是,我認為您已經放棄了完全一致的行為,因為您假設 Powershell 的等效行為與sed
的性能相同。
如果您想要實際的sed
進行更換,我會考慮使用 Windows Linux 子系統。 顯然,這需要用戶安裝 WLS。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.