簡體   English   中英

抑制織物運行輸出的簡單方法?

[英]Easy way to suppress output of fabric run?

我在遠程機器上運行命令:

remote_output = run('mysqldump --no-data --user=username --password={0} database'.format(password))

我想捕獲輸出,但不想將其全部打印到屏幕上。 什么是最簡單的方法來做到這一點?

聽起來像管理輸出部分是您正在尋找的。

要隱藏控制台的輸出,請嘗試以下操作:

from __future__ import with_statement
from fabric.api import hide, run, get

with hide('output'):
    run('mysqldump --no-data test | tee test.create_table')
    get('~/test.create_table', '~/test.create_table')

以下是示例結果:

No hosts found. Please specify (single) host string for connection: 192.168.6.142
[192.168.6.142] run: mysqldump --no-data test | tee test.create_table
[192.168.6.142] download: /home/quanta/test.create_table <- /home/quanta/test.create_table

如果您想隱藏日志中的所有內容並避免在命令失敗時結構拋出異常,請嘗試此操作:

from __future__ import with_statement
from fabric.api import env,run,hide,settings

env.host_string = 'username@servernameorip'
env.key_filename = '/path/to/key.pem'

def exec_remote_cmd(cmd):
    with hide('output','running','warnings'), settings(warn_only=True):
        return run(cmd)

之后,您可以檢查命令結果,如下例所示:

cmd_list = ['ls', 'lss']
for cmd in cmd_list:
    result = exec_remote_cmd(cmd)
    if result.succeeded:
        sys.stdout.write('\n* Command succeeded: '+cmd+'\n')
        sys.stdout.write(result+"\n")
    else:
        sys.stdout.write('\n* Command failed: '+cmd+'\n')
        sys.stdout.write(result+"\n")

這將是程序的控制台輸出(注意沒有來自結構的日志消息):

* Command succeeded: ls
Desktop    espaiorgcats.sql  Pictures   Public     Videos
Documents  examples.desktop  projectes  scripts
Downloads  Music         prueba Templates

* Command failed: lss
/bin/bash: lss: command not found

對於fabric==2.4.0,您可以使用以下邏輯隱藏輸出

conn = Connection(host="your-host", user="your-user")
result = conn.run('your_command', hide=True)
result.stdout.strip()  # here you can get the output

正如其他答案所暗示的那樣,在問題提出 8 年后, fabric.api不再存在(在撰寫本文時, fabric==2.5.0 )。 然而,這里的下一個最新答案意味着為每個.run()調用提供hide=True是唯一/可接受的方法。

不滿意我去挖掘一個合理的等價於一個我只能指定一次的上下文。 感覺仍然應該有一種使用invoke.context.Context的方法,但我不想再花在這上面了,我能找到的最簡單的方法是使用invoke.config.Config ,我們可以通過fabric.config.Config訪問它fabric.config.Config無需任何額外的導入。

>>> import fabric

>>> c = fabric.Connection(
...     "foo.example.com",
...     config=fabric.config.Config(overrides={"run": {"hide": True}}),
... )

>>> result = c.run("hostname")

>>> result.stdout.strip()
'foo.example.com'

從 Fabric 2.6.0 開始, hiderun參數不可用。

擴展@cfillol 和@samuel-harmer 的建議,使用fabric.Config可能是一種更簡單的方法:

   >>> import fabric

   >>> conf = fabric.Config()
   >>> conf.run.hide = True
   >>> conf.run.warn = True

   >>> c = fabric.Connection(
   ...     "foo.example.com",
   ...     config=conf
   ... )

   >>> result = c.run("hostname")

這樣就不會打印命令輸出,也不會在命令失敗時拋出異常。

暫無
暫無

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

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