2

I need to implement an external application to calculate CRC values for Modbus communication. The executable requires an input string and gives back output like this:

CRC16 = 0x67ED / 26605
CRC16 (Modbus) = 0x7CED / 31981

I call the programm and afterwards type in the input manually.

p = Popen(["some_file.exe", "-x"], stdin=PIPE)
p.communicate("some_string")

This is working fine so far.

However, I want to save the output to a variable or something (no extra file) for further uses.

I know there are the stdout and stderr arguments, but when typing

p = Popen([file, "-x"], stdin=PIPE, stdout=PIPE, stderr=PIPE)

nothing happens at all.

Does anyone has an idea what to do?

Thanks in advance.

PS: Using Python 2.7 on Windows 7.

mulm
  • 59
  • 3
  • 11

2 Answers2

1

To get the output of ls, use stdout=subprocess.PIPE.

proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
output = proc.stdout.read()
print output

Obtained from: Pipe subprocess standard output to a variable

NOTE:

If you use stdin as PIPE you must assign a value, like in this example:

grep = Popen('grep ntp'.split(), stdin=PIPE, stdout=PIPE)
ls = Popen('ls /etc'.split(), stdout=grep.stdin)
output = grep.communicate()[0]

if value is given by console using a PIPE, you must assign the stdin value reading sys.stdin

Community
  • 1
  • 1
Jose F. Gomez
  • 178
  • 1
  • 6
  • Thanks for your response. I dont know, but this does not seem to work. I need to give an input to the programm, so there needs to be a `stdin=PIPE`. Using just this argument is fine, but adding the `stdout=PIPE` is not. I dont even get to the point where I can write to a variable `output=...` – mulm Nov 10 '16 at 12:41
  • @mulm if you use `stdin=PIPE` you must assign a value to stdin, else it will be null. – Jose F. Gomez Nov 10 '16 at 15:28
1

Ok, I figured it out.

It says in an older post: How do I write to a Python subprocess' stdin?

The p.communicate() just waits for the input in the following form:

p = Popen(["some_file.exe", "-x"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
output = p.communicate(input="some_string")[0]

Then output has all the information that is received.

Community
  • 1
  • 1
mulm
  • 59
  • 3
  • 11