Python equivalent of piping file output to gzip in Perl using a pipe

后端 未结 5 741
南方客
南方客 2021-02-14 02:13

I need to figure out how to write file output to a compressed file in Python, similar to the two-liner below:

open ZIPPED, \"| gzip -c > zipped.gz\";
print ZI         


        
5条回答
  •  广开言路
    2021-02-14 02:30

    In addition to @srgerg's answer I want to apply same approach by disabling shell option shell=False, which is also done on @Moishe Lettvin's answer and recommended on (https://stackoverflow.com/a/3172488/2402577).

    import subprocess
    def zip():
        f = open("zipped.gz", "w")
        p1 = subprocess.Popen(["echo", "Hello World"], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(["gzip", "-9c"], stdin=p1.stdout, stdout=f)
        p1.stdout.close()
        p2.communicate()
        f.close()
    

    Please not that originally I am using this p1s output for git diff as:

    p1 = subprocess.Popen(["git", "diff"], stdout=subprocess.PIPE)

提交回复
热议问题