Any way to execute a piped command in Python using subprocess module, without using shell=True?

后端 未结 4 1420
别跟我提以往
别跟我提以往 2020-12-28 09:27

I want to run a piped command line linux/bash command from Python, which first tars files, and then splits the tar file. The command would look like something this in bash:<

4条回答
  •  臣服心动
    2020-12-28 09:51

    If you want to avoid using shell=True, you can manually use subprocess pipes.

    from subprocess import Popen, PIPE
    p1 = Popen(["tar", "-cvf", "-", "path_to_archive"], stdout=PIPE)
    p2 = Popen(["split", "-b", "20m", "-d", "-a", "5", "-", "'archive.tar.split'"], stdin=p1.stdout, stdout=PIPE)
    output = p2.communicate()[0]
    

    Note that if you do not use the shell, you will not have access to expansion of globbing characters like *. Instead you can use the glob module.

提交回复
热议问题