根据
this
回答我可以执行
.bat
用Python编写的文件。有可能不只是执行
.蝙蝠
文件,但也发送一个字符串作为参数,这将在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
1
意思是,出了问题。是的,因为Java程序看起来是这样的:
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
在Python中,
output.txt
是空的。我做错什么了?