简体   繁体   中英

Python subprocess.run shell kwarg behavior

There has been a lot of questions regarding shell keyword argument. But I still don't really get it especially if we use the sequence argument instead of the string.

My understanding is that if shell=False , the subprocess module will run the executable in args[0] and pass the rest as arguments to the executable. But if we run it with shell=True , it will be ran as something like "sh -c {}".format(format_escaping(args)) .

But why does this happen?

# Ran in OSX

subprocess.run(["touch", "12; touch 34"]) # successfuly make the file '12; touch 34'

subprocess.run(["touch", "56; touch 78"], shell=True) # does not work:
# usage:
# touch [-A [-][[hh]mm]SS] [-acfhm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ...
# CompletedProcess(args=['touch', '123; touch 456'], returncode=1)

What actually happen in subprocess.run(["touch", "56; touch 79"], shell=True) ?

我认为使用shell=True ,成功操作只会首先运行touch的第一个parameter ,因此您会从命令中获取帮助消息,而是尝试如下操作:

subprocess.run("touch 56; touch 78", shell=True)

The behavior when you pass in a list with shell=True is platform-dependent. On Unix-like platforms, Python simply passes in the first argument of the list. On Windows, it happens to work, though it probably shouldn't.

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