【问题标题】:How to pass a json object or string to a process [closed]如何将json对象或字符串传递给进程[关闭]
【发布时间】:2014-06-06 17:43:40
【问题描述】:

我有一个程序可以根据接收到的数据执行其他 python 脚本。 它接收到的数据是 json 格式,对那些执行的脚本很有帮助。

这就是为什么我希望这些脚本以某种方式接收 json。我想过使用Popen 使用subprocess 模块来完成它,但我认为它不会起作用,因为我必须发送一个转义字符串或一个json 对象(在 json.loads() 方法之后)。 我也可以将 json 写入文件并读取它,但这似乎是个糟糕的选择。

那么我该如何优雅地实现这一点呢?

【问题讨论】:

  • 查看zmq for python。它提供了一个简单的接口,用于仅使用您机器上的端口在任何进程架构之间发送序列化数据。
  • 您可以通过 STDIN 发送序列化的 JSON。
  • 使用Subprocess.Popen()?
  • @Shookie 父进程会同时运行多个子进程,还是一次只有一个子进程?
  • @cpburnz - 目前将是一个。

标签: python json


【解决方案1】:

如果一次只有一个子进程,并且父进程会等待子进程完成,则可以使用Popen.communicate()。示例:

# Create child with a pipe to STDIN.
child = subprocess.Popen(..., stdin=subprocess.PIPE)

# Send JSON to child's STDIN.
# - WARNING: This will block the parent from doing anything else until the
#   child process finishes
child.communicate(json_str)

然后,在子进程中(如果是python的话),可以用:

# Read JSON from STDIN.
json_str = sys.stdin.read()

或者,如果您想要更复杂的用途,即父进程可以多次写入多个子进程,那么在父进程中:

# Create child with a pipe to STDIN.
child = subprocess.Popen(..., stdin=subprocess.PIPE)

# Serialize and send JSON as a single line (the default is no indentation).
json.dump(data, child.stdin)
child.stdin.write('\n')

# If you will not write any more to the child.
child.stdin.close()

然后,在孩子中,您可以根据需要阅读每一行:

# Read a line, process it, and do it again.
for json_line in sys.stdin:
    data = json.loads(json_line)
    # Handle received data.

【讨论】:

  • 由于json被转义所以不会有问题,所以它会一直读到第一个新行吗?
  • @Shookie 这取决于。如果你做一个完整的.read()(等待 STDIN 被关闭),JSON 可以有任意多的换行符。如果您希望 JSON 仅在一行上,则必须确保 JSON 在没有缩进的情况下进行序列化,在这种情况下您要使用 .readline()
  • 我已经按照你说的做了,但我似乎从subprocess 得到了childe_exception。难道是因为我的命令是python A/script.py的形式?另外,在你给出的第二个例子中,不是child.stdin而不是sys.stdin吗?
  • @Shookie 你能把整个例外放在你的问题中,或者看看this,如果你遇到的是这种情况?是的,应该是child.stdin 而不是sys.stdin
猜你喜欢
  • 2019-11-16
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 2017-12-08
相关资源
最近更新 更多