17.1. subprocess
— 子进程管理
2.4 新版功能.
subprocess
模块允许你生成新的进程,连接它们的输入、输出、错误管道,并且获取它们的返回码。此模块打算代替一些老旧的模块与功能:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
在subprocess-replacements 部分介绍了这个模块怎么替代旧的功能。
参见:POSIX users (Linux, BSD, etc.) are strongly encouraged to install and use the much more recent subprocess32 module instead of the version included with python 2.7. It is a drop in replacement with better behavior in many situations.
PEP 324 – 提出 subprocess 模块的 PEP
17.1.1. 使用 subprocess
模块
推荐直接使用便捷的函数subprocess.call()。当无法满足需要时,可以使用更高级的用法 Popen
函数。
subprocess.call
(args, ***, stdin=None, stdout=None, stderr=None, shell=False)
args是要执行的命令。等待命令运行完成,然后返回returncode
属性。
The arguments shown above are merely the most common ones, described below in 常用参数 (hence the slightly odd notation in the abbreviated signature). The full function signature is the same as that of the Popen
constructor - this functions passes all supplied arguments directly through to that interface.
示例:
>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1
警告:Using
shell=True
can be a security hazard. See the warning under 常用参数 for details.
注解:Do not use
stdout=PIPE
orstderr=PIPE
with this function as that can deadlock based on the child process output volume. UsePopen
with thecommunicate()
method when you need pipes.
subprocess.check_call
(args, ***, stdin=None, stdout=None, stderr=None, shell=False)
使用这些参数运行命令。等待运行命令完成后,如果返回状态码是‘0’则返回,否则跑出 CalledProcessError
异常。CalledProcessError
异常包含 returncode
的属性。
The arguments shown above are merely the most common ones, described below in 常用参数 (hence the slightly odd notation in the abbreviated signature). The full function signature is the same as that of the Popen
constructor - this functions passes all supplied arguments directly through to that interface.
示例:
>>> subprocess.check_call(["ls", "-l"])
0
>>> subprocess.check_call("exit 1", shell=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
2.5 新版功能.
警告: Using
shell=True
can be a security hazard. See the warning under 常用参数 for details.
注解: Do not use
stdout=PIPE
orstderr=PIPE
with this function as that can deadlock based on the child process output volume. UsePopen
with thecommunicate()
method when you need pipes.
subprocess.check_output
(args, ***, stdin=None, stderr=None, shell=False, universal_newlines=False)
使用这些参数运行命令,返回的输出是一个字节字符串。
如果返回状态码是非0则会抛出 CalledProcessError
异常。 CalledProcessError
异常,包含返回状态码存在returncode
对象中,还有所有的输出存在output
对象中。
The arguments shown above are merely the most common ones, described below in 常用参数 (hence the slightly odd notation in the abbreviated signature). The full function signature is largely the same as that of the Popen
constructor, except that stdout is not permitted as it is used internally. All other supplied arguments are passed directly through to the Popen
constructor.
示例:
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'
>>> subprocess.check_output("exit 1", shell=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
To also capture standard error in the result, use stderr=subprocess.STDOUT
:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
2.7 新版功能.
警告: Using
shell=True
can be a security hazard. See the warning under 常用参数 for details.
注解: Do not use
stderr=PIPE
with this function as that can deadlock based on the child process error volume. UsePopen
with thecommunicate()
method when you need a stderr pipe.
subprocess.PIPE
特殊值可以通过stdin, stdout或者stderr参数传给Popen
,还可以通过连接多个输入输出标准流,构建一个通道。
subprocess.STDOUT
可被 Popen
的 stdin , stdout 或者 stderr 参数使用的特殊值, 表示标准错误与标准输出使用同一句柄。
exception subprocess.``CalledProcessError
当使用check_call()
和 check_output()
运行进行抛出异常时,会返回非0退出码。
returncode
子进程的退出状态
cmd
用于创建子进程的指令。
使用 check_output()
抛出异常时,包含子进程的输出信息,否则是“None”。
17.1.1.1. 常用参数
为了支持丰富的使用案例, Popen
的构造函数(以及方便的函数)接受大量可选的参数。对于大多数典型的用例,许多参数可以被安全地留以它们的默认值。通常需要的参数有:
args 被所有调用需要,应当为一个字符串,或者一个程序参数序列。提供一个参数序列通常更好,它可以更小心地使用参数中的转义字符以及引用(例如允许文件名中的空格)。如果传递一个简单的字符串,则 shell 参数必须为
True
(见下文)或者该字符串中将被运行的程序名必须用简单的命名而不指定任何参数。stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are
PIPE
, an existing file descriptor (a positive integer), an existing file object, andNone
.PIPE
indicates that a new pipe to the child should be created. With the default settings ofNone
, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can beSTDOUT
, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.When stdout or stderr are pipes and universal_newlines is
True
then all line endings will be converted to'\n'
as described for the universal newlines'U'
mode argument toopen()
.如果 shell 设为
True
,,则使用 shell 执行指定的指令。如果您主要使用 Python 增强的控制流(它比大多数系统 shell 提供的强大),并且仍然希望方便地使用其他 shell 功能,如 shell 管道、文件通配符、环境变量展开以及~
展开到用户家目录,这将非常有用。但是,注意 Python 自己也实现了许多类似 shell 的特性(例如glob
,fnmatch
,os.walk()
,os.path.expandvars()
,os.path.expanduser()
和shutil
)。警告: Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of
shell=True
is strongly discouraged in cases where the command string is constructed from external input:>>> from subprocess import call >>> filename = input("What file would you like to display?\n") What file would you like to display? non_existent; rm -rf / # >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
shell=False
disables all shell based features, but does not suffer from this vulnerability; see the Note in thePopen
constructor documentation for helpful hints in gettingshell=False
to work.
When usingshell=True
,pipes.quote()
can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands.
这些选项以及所有其他选项在 Popen
构造函数文档中有更详细的描述。
17.1.1.2. Popen 构造函数
此模块的底层的进程创建与管理由 Popen
类处理。它提供了很大的灵活性,因此开发者能够处理未被便利函数覆盖的不常见用例。
class subprocess.Popen
(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
Execute a child program in a new process. On Unix, the class uses os.execvp()
-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess()
function. The arguments to Popen
are as follows.
args 应当是一个程序的参数列表或者一个简单的字符串。默认情况下,如果 args 是一个序列,将运行的程序是此序列的第一项。如果 args 是一个字符串,解释是平台相关的,如下所述。有关默认行为的其他差异,见 shell 和 executable 参数。除非另有说明,推荐将 args 作为序列传递。
On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program.
注解:
shlex.split()
can be useful when determining the correct tokenization for args, especially in complex cases:>>> import shlex, subprocess >>> command_line = raw_input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print args ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success!
特别注意,由 shell 中的空格分隔的选项(例如 -input)和参数(例如 eggs.txt )位于分开的列表元素中,而在需要时使用引号或反斜杠转义的参数在 shell (例如包含空格的文件名或上面显示的 echo 命令)是单独的列表元素。
在 Windows,如果 args 是一个序列,他将通过一个在 Converting an argument sequence to a string on Windows 描述的方式被转换为一个字符串。这是因为底层的 CreateProcess()
只处理字符串。
参数 shell (默认为 False
)指定是否使用 shell 执行程序。如果 shell 为 True
,更推荐将 args 作为字符串传递而非序列。
On Unix with shell=True
, the shell defaults to /bin/sh
. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen
does the equivalent of:
Popen(['/bin/sh', '-c', args[0], args[1], ...])
在 Windows,使用 shell=True
,环境变量 COMSPEC
指定了默认 shell。在 Windows 你唯一需要指定 shell=True
的情况是你想要执行内置在 shell 中的命令(例如 dir 或者 copy)。在运行一个批处理文件或者基于控制台的可执行文件时,不需要 shell=True
。
警告: Passing
shell=True
can be a security hazard if combined with untrusted input. See the warning under 常用参数 for details.
bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: 0
means unbuffered, 1
means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0
(unbuffered).
注解: If you experience performance issues, it is recommended that you try to enable buffering by setting bufsize to either -1 or a large enough positive value (such as 4096).
The executable argument specifies a replacement program to execute. It is very seldom needed. When shell=False
, executable replaces the program to execute specified by args. However, the original args is still passed to the program. Most programs treat the program specified by args as the command name, which can then be different from the program actually executed. On Unix, the args name becomes the display name for the executable in utilities such as ps. If shell=True
, on Unix the executable argument specifies a replacement shell for the default /bin/sh
.
stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE
, an existing file descriptor (a positive integer), an existing file object, and None
. PIPE
indicates that a new pipe to the child should be created. With the default settings of None
, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT
, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.
If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. (Unix only)
If close_fds is true, all file descriptors except 0
, 1
and 2
will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr.
If cwd is not None
, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.
If env is not None
, it must be a mapping that defines the environment variables for the new process; these are used instead of inheriting the current process’ environment, which is the default behavior.
注解: 如果指定, env 必须提供所有被子进程需求的变量。在 Windows,为了运行一个 side-by-side assembly ,指定的 env 必须 包含一个有效的
SystemRoot
。
If universal_newlines is True
, the file objects stdout and stderr are opened as text files in universal newlines mode. Lines may be terminated by any of '\n'
, the Unix end-of-line convention, '\r'
, the old Macintosh convention or '\r\n'
, the Windows convention. All of these external representations are seen as '\n'
by the Python program.
注解: This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects
stdout
,stdin
andstderr
are not updated by the communicate() method.
If given, startupinfo will be a STARTUPINFO
object, which is passed to the underlying CreateProcess
function. creationflags, if given, can be CREATE_NEW_CONSOLE
or CREATE_NEW_PROCESS_GROUP
. (Windows only)
17.1.1.3. 异常
Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called child_traceback
, which is a string containing traceback information from the child’s point of view.
最常见的被抛出异常是 OSError
。例如,当尝试执行一个不存在的文件时就会发生。应用程序需要为 OSError
异常做好准备。
如果 Popen
调用时有无效的参数,则一个 ValueError
将被抛出。
check_all()
与 check_output()
在调用的进程返回非零退出码时将抛出 CalledProcessError
。
17.1.1.4. Security
Unlike some other popen functions, this implementation will never call a system shell implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Obviously, if the shell is invoked explicitly, then it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately.
17.1.2. Popen 对象
Popen
类的实例拥有以下方法:
Check if child process has terminated. Set and return returncode
attribute.
等待子进程被终止。设置并返回 returncode
属性。
警告: This will deadlock when using
stdout=PIPE
and/orstderr=PIPE
and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Usecommunicate()
to avoid that.
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None
, if no data should be sent to the child.
communicate()
returns a tuple (stdoutdata, stderrdata)
.
注意如果你想要向进程的 stdin 传输数据,你需要通过 stdin=PIPE
创建此 Popen 对象。类似的,要从结果元组获取任何非 None
值,你同样需要设置 stdout=PIPE
或者 stderr=PIPE
。
注解: 内存里数据读取是缓冲的,所以如果数据尺寸过大或无限,不要使用此方法。
将信号 signal 发送给子进程。
注解: 在 Windows, SIGTERM 是一个
terminate()
的别名。 CTRL_C_EVENT 和 CTRL_BREAK_EVENT 可以被发送给以包含CREATE_NEW_PROCESS
的 creationflags 形参启动的进程。
2.6 新版功能.
Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess()
is called to stop the child.
2.6 新版功能.
Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows kill()
is an alias for terminate()
.
2.6 新版功能.
以下属性也是可用的:
警告: 使用
communicate()
而非.stdin.write
,.stdout.read
或者.stderr.read
来避免由于任意其他 OS 管道缓冲区被子进程填满阻塞而导致的死锁。
Popen.stdin
If the stdin argument was PIPE
, this attribute is a file object that provides input to the child process. Otherwise, it is None
.
If the stdout argument was PIPE
, this attribute is a file object that provides output from the child process. Otherwise, it is None
.
If the stderr argument was PIPE
, this attribute is a file object that provides error output from the child process. Otherwise, it is None
.
子进程的进程号。
注意如果你设置了 shell 参数为 True
,则这是生成的子 shell 的进程号。
此进程的退出码,由 poll()
和 wait()
设置(以及直接由 communicate()
设置)。一个 None
值 表示此进程仍未结束。
A negative value -N
indicates that the child was terminated by signal N
(Unix only).
17.1.3. Windows Popen 助手
STARTUPINFO
类和以下常数仅在 Windows 有效。
class subprocess.STARTUPINFO
Partial support of the Windows STARTUPINFO structure is used for Popen
creation.
一个位字段,用于确定进程在创建窗口时是否使用某些 STARTUPINFO
属性。
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
如果 dwFlags
被指定为 STARTF_USESTDHANDLES
,则此属性是进程的标准输入句柄,如果 STARTF_USESTDHANDLES
未指定,则默认的标准输入是键盘缓冲区。
如果 dwFlags
被指定为 STARTF_USESTDHANDLES
,则此属性是进程的标准输出句柄。除此之外,此此属性将被忽略并且默认标准输出是控制台窗口缓冲区。
如果 dwFlags
被指定为 STARTF_USESTDHANDLES
,则此属性是进程的标准错误句柄。除此之外,此属性将被忽略并且默认标准错误为控制台窗口的缓冲区。
如果 dwFlags
指定了 STARTF_USESHOWWINDOW
,此属性可为能被指定为 函数 ShowWindow 的nCmdShow 的形参的任意值,除了 SW_SHOWDEFAULT
。如此之外,此属性被忽略。
SW_HIDE
被提供给此属性。它在 Popen
由 shell=True
调用时使用。
17.1.3.1. Constants
subprocess
模块曝出以下常数。
标准输入设备,这是控制台输入缓冲区 `CONIN。
subprocess.``STD_OUTPUT_HANDLE
标准输出设备。最初,这是活动控制台屏幕缓冲区 `CONOUT。
标准错误设备。最初,这是活动控制台屏幕缓冲区 `CONOUT。
隐藏窗口。另一个窗口将被激活。
subprocess.``STARTF_USESTDHANDLES
Specifies that the STARTUPINFO.hStdInput
, STARTUPINFO.hStdOutput
, and STARTUPINFO.hStdError
attributes contain additional information.
subprocess.``STARTF_USESHOWWINDOW
Specifies that the STARTUPINFO.wShowWindow
attribute contains additional information.
subprocess.``CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting its parent’s console (the default).
This flag is always set when Popen
is created with shell=True
.
subprocess.``CREATE_NEW_PROCESS_GROUP
A Popen
creationflags
parameter to specify that a new process group will be created. This flag is necessary for using os.kill()
on the subprocess.
This flag is ignored if CREATE_NEW_CONSOLE
is specified.
17.1.4. Replacing Older Functions with the subprocess
Module
In this section, “a becomes b” means that b can be used as a replacement for a.
注解: All “a” functions in this section fail (more or less) silently if the executed program cannot be found; the “b” replacements raise
OSError
instead.
In addition, the replacements using check_output()
will fail with a CalledProcessError
if the requested operation produces a non-zero return code. The output is still available as the output
attribute of the raised exception.
In the following examples, we assume that the relevant functions have already been imported from the subprocess
module.
17.1.4.1. Replacing /bin/sh shell backquote
output=`mycmd myarg`
becomes:
output = check_output(["mycmd", "myarg"])
17.1.4.2. Replacing shell pipeline
output=`dmesg | grep hda`
becomes:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.
Alternatively, for trusted input, the shell’s own pipeline support may still be used directly:
output=`dmesg | grep hda`
becomes:
output=check_output("dmesg | grep hda", shell=True)
17.1.4.3. Replacing os.system()
status = os.system("mycmd" + " myarg")
# becomes
status = subprocess.call("mycmd" + " myarg", shell=True)
注释:
- Calling the program through the shell is usually not required.
A more realistic example would look like this:
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError as e:
print >>sys.stderr, "Execution failed:", e
17.1.4.4. Replacing the os.spawn
family
P_NOWAIT example:
pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid
P_WAIT example:
retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])
Vector example:
os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])
Environment example:
os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
17.1.4.5. Replacing os.popen()
, os.popen2()
, os.popen3()
pipe = os.popen("cmd", 'r', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
pipe = os.popen("cmd", 'w', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
(child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
(child_stdin,
child_stdout,
child_stderr) = os.popen3("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
child_stdout,
child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as the command to execute, in which case arguments will be passed directly to the program without shell intervention. This usage can be replaced as follows:
(child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
bufsize)
==>
p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
Return code handling translates as follows:
pipe = os.popen("cmd", 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
print "There were some errors"
==>
process = Popen("cmd", shell=True, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
print "There were some errors"
17.1.4.6. Replacing functions from the popen2
module
(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
On Unix, popen2 also accepts a sequence as the command to execute, in which case arguments will be passed directly to the program without shell intervention. This usage can be replaced as follows:
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
popen2.Popen3
and popen2.Popen4
basically work as subprocess.Popen
, except that:
Popen
raises an exception if the execution fails.the capturestderr argument is replaced with the stderr argument.
stdin=PIPE
andstdout=PIPE
must be specified.popen2 closes all file descriptors by default, but you have to specify
close_fds=True
withPopen
.
17.1.5. 注释
17.1.5.1. Converting an argument sequence to a string on Windows
On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):
Arguments are delimited by white space, which is either a space or a tab.
A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.
A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.