我正在远程机器上运行命令:
remote_output = run('mysqldump --no-data --user=username --password={0} database'.format(password))
Run Code Online (Sandbox Code Playgroud)
我想捕获输出,但没有全部打印到屏幕上.最简单的方法是什么?
qua*_*nta 33
这听起来像管理输出部分是你正在寻找的.
要隐藏控制台的输出,请尝试以下操作:
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')
Run Code Online (Sandbox Code Playgroud)
Belows是样本结果:
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
Run Code Online (Sandbox Code Playgroud)
cfi*_*lol 19
如果要隐藏日志中的所有内容并避免在命令失败时抛出异常,请尝试此操作:
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)
Run Code Online (Sandbox Code Playgroud)
之后,您可以检查命令结果,如下例所示:
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")
Run Code Online (Sandbox Code Playgroud)
这将是程序的控制台输出(观察到没有来自结构的日志消息):
* 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
正如其他答案所暗示的那样,在问题提出 8 年后,fabric.api
它不再存在(截至撰写本文时)。fabric==2.5.0
然而,这里的下一个最新答案意味着hide=True
向每个.run()
呼叫提供是唯一/可接受的方式。
由于不满足,我开始寻找一个合理的等同于我只能指定一次的上下文。感觉应该仍然有一种使用 an 的方法invoke.context.Context
,但我不想再花更多的时间在这上面,我能找到的最简单的方法是使用invoke.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'
Run Code Online (Sandbox Code Playgroud)
对于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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28010 次 |
最近记录: |