python - 如何在Python中从shell中获取变量?

标签 python shell variables

我正在编写一个脚本,需要通过其运行的 Linux 计算机的本地 dbus 来利用 Java 守护进程。这个守护进程特别会返回一个我想要的元组数组,以便我可以在我的代码中解析/使用稍后的信息。我希望这段代码能够同时从多台机器获取这个值,但问题是我认为真正从我通过 ssh 进入的终端获取返回/退出值的唯一方法是通过解析 stdout 的输出。我不想这样做,我更愿意获得实际的变量。现在我有这个:

import os
message = "import dbus, sys\nbus=dbus.SystemBus()\nremote_object=bus.get_object('daemon.location', '/daemon')\ncontroller=dbus.Interface(remote_object, 'daemon.path')\nsys.exit(controller.getValue())"
x = os.system('echo \-e "%s" \| ssh %s python' %(message, ip))

在此示例中,当我运行“controller.getValue()”时,它返回一个元组数组。我正在尝试找出一种方法来获取该数组。当使用诸如 popen 之类的东西时,它将 stdout 中的输出通过管道传输到文件中并将其返回给您,这样您就可以获得与数组等效的字符串。我想弄清楚的是如何获取实际的数组。就好像将退出 ssh tty 时返回的变量传递到我的代码中一样。有什么想法吗?

最佳答案

如果没有共享内存,就无法避免序列化。线路上只有字节。 您可以使用一个对您隐藏它的库,例如 execnet模块:

#!/usr/bin/env python
import execnet

gw = execnet.makegateway("ssh=user@host")
channel = gw.remote_exec("""
import dbus, sys

bus = dbus.SystemBus()
remote_object = bus.get_object('daemon.location', '/daemon')
controller = dbus.Interface(remote_object, 'daemon.path')

channel.send(controller.getValue())
""")
tuple_ = channel.receive()
print tuple_
print tuple_[0]

但是使用 ast.literal_eval() 自己解析简单的元组值很容易来自标准库:

#fabfile.py
import ast
from fabric.api import run

def getcontroller():
    """Return controller value."""
    cmd = """
import dbus, sys

bus = dbus.SystemBus()
remote_object = bus.get_object('daemon.location', '/daemon')
controller = dbus.Interface(remote_object, 'daemon.path')

print repr(controller.getValue())
""" #NOTE: you must escape all quotation marks
    output = run('python -c "%s"' % cmd)
    tuple_ = ast.literal_eval(output)
    print tuple_[0]

示例:$ fab getcontroller -H user@host

这里我使用了fabric在远程主机上运行命令。

如果另一端不生成 Python 文字,您可以使用 JSON 作为序列化格式:

>>> import json
>>> t = (1, "a")
>>> json.dumps(t)
'[1, "a"]'
>>> json.loads(_)
[1, u'a']
>>>

关于python - 如何在Python中从shell中获取变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7730991/

相关文章:

linux - Grep 在反引号内寻找美元符号

javascript - 继续获取 "Unexpected token ,"以及变量中的坐标

php - 公共(public)静态变量值

python - Pandas 将两个单独的列转换为单个日期时间列?

javascript - 使用 python 抓取动态加载的网站

python ->属性错误 : 'list' object has no attribute 'lower' (in a lowercase dataframe)

linux - if语句中的shell条件

python - 处理 OCR 导入

linux - 数组值的总数

c - C 中未初始化局部变量的默认值