首页 > 解决方案 > 试图在 Python 子进程中避免 shell=True

问题描述

我需要在 Python 程序中连接多个以相同名称开头的文件。我的想法是,在 bash shell 中,类似于

cat myfiles* > my_final_file

但是有两个 shell 运算符可以使用:*>. 这可以很容易地解决使用

subprocess.Popen("cat myfiles* > my_final_file", shell=True)

但是每个人都说,shell=True出于安全和便携性的原因,您必须避免使用。那我该如何执行那段代码呢?

标签: pythonsubprocesspopen

解决方案


您必须在 python 中扩展模式:

import glob
subprocess.check_call(['cat'] + glob.glob("myfiles*"), stdout=open("my_final_file", "wb"))

或者更好地在 python 中做所有事情:

with open("my_final_file", "wb") as output:
    for filename in glob.glob("myfiles*"):
        with open(filename, "rb") as inp:
            output.write(inp.read())

推荐阅读