使用' subprocess.run ',参数包含一个空格



在Python中使用subprocess.run时,我如何执行其中一个参数包含空格的命令?

例如,我想创建一个名称为test file(inc. space)的文件。在shell中,您可以这样做:

touch 'test file'

使用subprocess.run在Python我已经尝试:

import subprocess
subprocess.run(["touch", "'test file'") # Creates a file called `'test file'` (inc. quotes)
subprocess.run(["touch", "test file") # Creates a file called `test me`
subprocess.run(["touch", "test", "file") # Creates two files `test` and `file`
subprocess.run(["touch", "'test", "file'") # Creates two files `'test` and `file'`

不需要使用引号来指定包含空格的参数,因为它被视为字符串文字,只需:

subprocess.run(["touch", "test file"])

创建一个名为test file的文件。

最新更新