Hex characters in arguments to Popen

时间:2015-10-30 21:36:01

标签: python

I am trying to pass a raw byte array to a process:

import subprocess
cmd = ["./input"]
cmd += "\x00"
subprocess.Popen(cmd)

However, this gives the error:

TypeError: execv() arg 2 must contain only strings

How do I solve this?

3 个答案:

答案 0 :(得分:1)

This problem only occurs for me when you include the null terminator (\x00). For every other value, it works. Try this:

for a in range(256):
    cmd = ["echo",chr(a)]
    try:
        c = subprocess.Popen(cmd)
    except TypeError:
        print(a)

This only gave me one value: 0. At a guess, I would say that python just gets confused when you have double null terminators.

答案 1 :(得分:0)

You should escape your slash by using cmd += '\\x00'

答案 2 :(得分:0)

That's equivalent to trying to pass the raw byte array as a command line argument, which is a bit unusual.

If you're writing the application that you're calling with popen, I suggest passing the data via stdin, see: Python - How do I pass a string into subprocess.Popen (using the stdin argument)?