[英]Executing A complex Shell command read as String from a File in Python
我有一個配置文件,用戶可以在其中指定一組shell命令。 命令基本上是由管道分隔的Shell命令組成的鏈。
CMD1 = grep "SomeOtherString" | grep "XX" | cut -d":" -f9 | cut -d"," -f1
CMD2 = grep "SomeOtherString" | tail -1| cut -d":" -f9 | cut -d"," -f1 | cut -d"[" -f2 | cut -d"]" -f1
我能夠讀取Python腳本中的命令。 我的問題是我將如何在Python中運行這些讀取的命令字符串並獲得輸出。
任何帶有subprocess
, plumbum
, sh
解決方案都是可以接受的。
output = subprocess.check_output(output)
需要注意的是,與其他子流程命令不同,如果返回非零錯誤代碼,則會引發subprocess.CalledProcessError。
您不需要這樣做,但是萬一它派上用場的話,我確實遇到了一次經驗,由於某種原因上述解決方案不起作用,因此,我做了以下工作。
stdout_fh = io.StringIO()
stderr_fh = io.StringIO()
with redirect_stderr(stderr_fh):
with redirect_stdout(stdout_fh):
subprocess.run(command, shell=True)
stderr = stderr_fh.getvalue()
stdout = stderr_fh.getvalue()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.