【问题标题】:Send a string as a parameter in python subprocess在 python 子进程中发送一个字符串作为参数
【发布时间】:2018-07-31 14:59:09
【问题描述】:

根据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

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();
}

在 Python 中执行 file.bat 后,output.txt 为空。我究竟做错了什么?

【问题讨论】:

  • 这是一个RTFM-kind 的答案...您必须使用包含“可执行文件”和每个参数的列表调用 Popen,例如p = subprocess.Popen([filepath,os.path.abspath('.\\file.txt')], stdout=subprocess.PIPE, stdin=subprocess.PIPE)。如果被调用的“程序”从stdin读取,则可以使用communicate
  • 不明白为什么需要batch-file
  • @Squashman 我在调用mvn clean package 命令时变成了这个文件
  • @LohmarASHAR 感谢您的反馈!我会尝试你的建议并告诉你它是否有效

标签: java python maven batch-file


【解决方案1】:

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

p = subprocess.Popen([filepath, os.path.abspath('.\\file.txt')], stdout=subprocess.PIPE, stdin=subprocess.PIPE)

附带说明,您应该/将仅在“可执行文件”启动“询问”输入(stdin)时使用.communicate(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2011-06-30
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多