在python子进程中将字符串作为参数发送

问题描述 投票:0回答:1

根据this的回答,我可以用Python执行.bat文件。是否有可能不仅执行.bat文件,还发送一个字符串作为参数,将在Java程序中使用?

我现在拥有的:

Python脚本:

import subprocess

filepath="C:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)

stdout, stderr = p.communicate()
print p.returncode # is 0 if success

Java程序:

public static void main(String[] args) {
    System.out.println("Hello world");
}

我想要的是:

Python脚本:

import subprocess

parameter = "C:\\path\\to\\some\\file.txt"
filepath="C:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE, parameter)

stdout, stderr = p.communicate()
print p.returncode # is 0 if success

Java程序:

public static void main(String[] args) {
    System.out.println("Hello world");
    System.out.println(args[1]); // prints 'C:\\path\\to\\some\\file.txt'
}

所以主要的想法是将python中的字符串作为参数发送到java程序并使用它。我试过的是:

import os
import subprocess

filepath = "C:\\Path\\to\\file.bat"
p = subprocess.Popen(filepath, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
grep_stdout = p.communicate(input=b"os.path.abspath('.\\file.txt')")[0]
print(grep_stdout.decode())
print(p.returncode)
print(os.path.abspath(".\\file.txt"))

输出:

1
C:\\path\\to\\file.txt

qazxsw poi意味着,出了点问题。它就是这样,因为Java程序看起来像这样:

1

在Python中执行public static void main(String[] args) throws IOException { String s = args[1]; // write 's' to a file, to see the result FileOutputStream outputStream = new FileOutputStream("C:\\path\\to\\output.txt"); byte[] strToBytes = s.getBytes(); outputStream.write(strToBytes); outputStream.close(); } 之后,file.bat是空的。我究竟做错了什么?

java python maven batch-file
1个回答
1
投票

您的代码中的问题是您以错误的方式调用output.txt。为了达到你想要的效果,正如subprocess.Popen所述,documentation应该用一个包含“可执行文件”的字符串列表和所有其他参数分别调用。更确切地说,在你的情况下它应该是:

Popen

作为旁注,你应该/只在“可执行文件”启动“询问”输入(stdin)时使用p = subprocess.Popen([filepath, os.path.abspath('.\\file.txt')], stdout=subprocess.PIPE, stdin=subprocess.PIPE)

© www.soinside.com 2019 - 2024. All rights reserved.