简体   繁体   中英

Trying to avoid shell=True in a Python subprocess

I need to concatenate multiple files that begin with the same name inside a Python program. My idea, in a bash shell, would be to something like

cat myfiles* > my_final_file

but there are two shell operators to use: * and > . This could be easily solved using

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

but everybody says the using shell=True is something you have to avoid for security and portability reasons. How can I execute that piece of code, then?

You have to expand the pattern in python:

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

or better do everything in 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM