According to this answer I can execute the .bat file in Python. Is it possible not only execute .bat file, but also send a string as a parameter, which will be used in Java programm?
What I have now:
Python script:
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 programm:
public static void main(String[] args) {
System.out.println("Hello world");
}
What I want to have:
Python script:
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 programm:
public static void main(String[] args) {
System.out.println("Hello world");
System.out.println(args[1]); // prints 'C:\\path\\to\\some\\file.txt'
}
So the main idea is to send a string from python as parameter to a java programm and use it. What I have tried is following:
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"))
Output:
1
C:\\path\\to\\file.txt
1 means, that something went wrong. And it is so, because Java programm looks like this:
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();
}
and after execution file.bat in Python, output.txt is empty. What am I doing wrong?
1 Answer 1
The problem in your code is that you are calling subprocess.Popen in the wrong way. In order to achieve what you want, as the documentation states, Popen should be called with a list of strings containing the "executable" and all the other arguments separately. More precisely, in your case it should be:
p = subprocess.Popen([filepath, os.path.abspath('.\\file.txt')], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
As a side note, you should/would use .communicate(...) only when the "executable" launched "asks" for input (stdin).
p = subprocess.Popen([filepath,os.path.abspath('.\\file.txt')], stdout=subprocess.PIPE, stdin=subprocess.PIPE). You can usecommunicateif the called "program" reads fromstdin.batch-file?mvn clean packagecommand