我在远程机器上运行一个命令:
remote_output = run('mysqldump --no-data --user=username --password={0} database'.format(password))我希望捕获输出,但不会将其全部打印到屏幕上。做这件事最简单的方法是什么?
发布于 2012-03-09 01:12:20
听起来Managing output部分就是你要找的。
要隐藏控制台的输出,请尝试执行以下操作:
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发布于 2019-11-05 18:41:02
对于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发布于 2020-12-13 22:25:33
正如其他答案暗示的那样,问题提出8年后,fabric.api已不复存在(在撰写本文时,为fabric==2.5.0)。然而,这里的下一个最新答案意味着为每个.run()调用提供hide=True是唯一/被接受的方法。
不满意的是,我开始挖掘一个合理的等价物,在这个上下文中,我只能指定一次。感觉应该还有一种使用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'https://stackoverflow.com/questions/9456419
复制相似问题