绕过子进程命令的大小限制

时间:2016-07-19 10:13:29

标签: python size subprocess buffer maxlength

我需要你的帮助来解决我的问题。我想使用子进程启动powershell命令。但是,使用的命令将非常长,因此它将大于缓冲区的大小。我做了很多测试,现在我无法找到一个好的解决方案。 我想将我的大缓冲区(它是base64内容)拆分成小缓冲区,但我不知道如何使用子进程。

例如,这是我的子进程调用:

a = "a" * 32716
command = ["powershell.exe", "/c", "$base64='%s'\n" % a, "Write-Host $base64"]
process = subprocess.Popen(command, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, universal_newlines=True)

如果变量" a "的大小有效。小于32717,如果它更大(例如:等于32717)我有以下错误: WindowsError:[错误87]参数不正确。如果它更大,我有这个错误: WindowsError:[错误206]文件名或扩展名太长

我试图拆分" 命令"变量为小缓冲区,但缓冲区的内容不是单元格,它是整个标签的串联,因此它不会改变问题。

command = ["powershell.exe", "/c", "$base64=" + small_buffer1, "$base64=$base64+" small_buffer2, etc.]

另一个想法是使用不同的子进程调用。问题是我无法连接变量,因为它不会在同一个PowerShell实例上定义。所以在子流程之间,我将失去" base64 "内容。

subprocess.Popen(["powershell.exe", "/c", "$base64='%s'\n" % a], stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
# $base64 will be empty
subprocess.Popen(["powershell.exe", "/c", "Write-Host $base64"], stderr=subprocess.STDOUT, stdin=subprocess.PIPE) 

如果有人有想法,那将是非常好的。我认为,可以定义一个powershell实例并将缓冲区作为交互式shell添加到其中。

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

我发现的解决方案很容易实现。目标是保持子进程打开并在stdin中写入缓冲区。 这是一个例子:

# keep the pipe open
p = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=True)

# initialize the powershell value
p.stdin.write("$data=\"\""+"\n")

# split the buffer to small buffers
size = 25000
tab = [veryLongLine[i:i+size] for i in range(0, len(veryLongLine), size)]
for t in tab:
    # concatenate small buffers to obtain the "veryLongLine" value
    p.stdin.write("$data+=\"%s\"\n" % t)

    # flush the buffer every time (the $data value is not flushed)        
    p.stdin.flush()

# write the output
p.stdin.write("Write-Host $data\n")

希望它会有所帮助!