python - 试图在 Python 子进程中避免 shell=True
问题描述
我需要在 Python 程序中连接多个以相同名称开头的文件。我的想法是,在 bash shell 中,类似于
cat myfiles* > my_final_file
但是有两个 shell 运算符可以使用:*
和>
. 这可以很容易地解决使用
subprocess.Popen("cat myfiles* > my_final_file", shell=True)
但是每个人都说,shell=True
出于安全和便携性的原因,您必须避免使用。那我该如何执行那段代码呢?
解决方案
您必须在 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())
推荐阅读
- java - Why does fetching results using "new Throwable().getStackTrace()[1].getMethodName()" termed as expensive?
- c# - Restsharp:自动映射查询参数
- php - 如何将 php ext dir 保存在变量中?
- python - Python animated cursor next to a printed line
- c - I got different output when using 2 different compilers
- ant - 从 css 文件中收集字符串并将它们保存到新的 css 文件中
- jupyter-notebook - 我可以恢复在 GCP Dataproc 中删除的 Jupyter 笔记本吗
- sql - 我的连接字符串中的服务器标记格式错误
- snakemake - How to have multiple users run the same pipeline in snakemake - metadata permissions issue
- javascript - MomentJS,如何忽略用户的本地时区,并使用