将PHP代码(proc_open)转换为Python(Popen)

时间:2018-04-15 13:59:25

标签: php python subprocess

我试图将这段PHP代码转换为Python。我已经弄清楚如何处理crc32b哈希,但我已经卡在proc_open()上了。你能救我一下吗?

我想要的是在Python代码中获取$pipeOutput的值。

PHP

$hashedData = strrev(hash("crc32b", $data, true)) . $data;
$xzBinary = trim(`which xz`);
$xzProcess = proc_open("$xzBinary '--format=raw' '--lzma1=lc=3,lp=0,pb=2,dict=128KiB' '-c' '-'", [
    0 => [
        "pipe",
        "r"
    ],
    1 => [
        "pipe",
        "w"
    ]
], $xzProcessPipes);
fwrite($xzProcessPipes[0], $hashedData);
fclose($xzProcessPipes[0]);
$pipeOutput = stream_get_contents($xzProcessPipes[1]);
fclose($xzProcessPipes[1]);
proc_close($xzProcess);

的Python

import zlib
from subprocess import Popen


def crc32b(x):
    h = zlib.crc32(x)
    x='%08X' % (h & 0xffffffff,)
    return x.lower()

data = 'some_data'

hashed_data = crc32b(data)[::-1]+data #strrev(hash("crc32b", $data, true)) . $data;
xz_binary = '//usr/bin/xz'
r = Popen([xz_binary, "--format=raw",'--lzma1=lc=3,lp=0,pb=2,dict=128KiB','-c','-'])

修改

hashed_data = crc32b(data)[::-1]+data
xz_binary = '//usr/bin/xz'
p = Popen([xz_binary, "--format=raw",'--lzma1=lc=3,lp=0,pb=2,dict=128KiB','-c','-'],stdin=PIPE, stdout=PIPE,stderr=PIPE)

p.communicate()
stdout_file = p.stdout
stdin_file = p.stdin
stdin_file.write(hashed_data)

stdin_file已关闭,但我不确定这是否是我应该做的

ValueError: I/O operation on closed file

0 个答案:

没有答案