gpt4 book ai didi

python - 使用 Python 的子进程模块包装 Java 程序的问题

转载 作者:行者123 更新时间:2023-11-28 16:49:15 25 4
gpt4 key购买 nike

我有一个小的 java 程序,我可以使用以下语法从命令行运行它:

java -jar EXEV.jar -s:myfile

这个 java 程序将一些数据打印到屏幕上,我想将 stdout 重定向到一个名为 output.txt 的文件中。

from subprocess import Popen, PIPE

def wrapper(*args):
process = Popen(list(args), stdout=PIPE)
process.communicate()[0]
return process

x = wrapper('java', '-jar', 'EXEV.jar', '-s:myfile', '>', 'output.txt')

当我运行上面的代码时,output.txt 永远不会被写入,Python 也不会抛出任何错误。谁能帮我解决问题?

最佳答案

您需要使用 stdout=output,其中 output 是一个用于写入“output.txt”的打开文件,并从命令中删除输出重定向,或者离开命令中的输出重定向并使用不带 stdout 参数的 shell=True:

选项 1:

from subprocess import Popen

def wrapper(*args):
output = open('output.txt', w)
process = Popen(list(args), stdout=output)
process.communicate()
output.close()
return process

x = wrapper('java', '-jar', 'EXEV.jar', '-s:myfile')

选项 2:

from subprocess import Popen

def wrapper(*args):
process = Popen(' '.join(args), shell=True)
process.communicate()
return process

x = wrapper('java', '-jar', 'EXEV.jar', '-s:myfile', '>', 'output.txt')

关于python - 使用 Python 的子进程模块包装 Java 程序的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9795249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com