0

我有一个 jar 文件,可以将数据发送到该文件进行处理,数据为 json 格式。 data_path是包含数据的文件的路径。下面的效果很好。但是我拥有的数据不会是文件,而是变量。下面的命令不适用于变量,它尝试读取作为文件的文字目录路径传递的数据。它会是一个不同的 bash 命令吗?或者我可以用 subprocess 模块做些什么?谢谢!

import subprocess as sub

cmd = "java -jar %s < %s" % (jar_path, data_path)
# send data in a var
# cmd = "java -jar %s < %s" % (jar_path, data)
proc = sub.Popen(cmd, stdin=sub.PIPE, stdout=sub.PIPE, shell=True)
(out, err) = proc.communicate()
4

1 回答 1

1

You can write it to a temporary file and pass that:

import tempfile

with tempfile.NamedTemporaryFile() as f:
    f.write(data)
    f.flush()
    cmd = "java -jar %s < %s" % (jar_path, f.name)
    ...

The temp file will delete itself when the context ends.

@FedorGogolev had deleted answers going for a Popen stdin approach that weren't quite working for your specific needs. But it was a good approach so I credit him, and thought I would add the working version of what he was going for...

import tempfile

with tempfile.TemporaryFile() as f:
    f.write(data)
    f.flush()
    f.seek(0)
    cmd = "java -jar %s" % jar_path
    p = subprocess.Popen(cmd, shell=True, stdin=f, stdout=subprocess.PIPE)
    ...

If you are passing the file object as the stdin arg you have to make sure to seek it to 0 position first.

于 2012-08-31T01:24:29.957 回答