使用Python os.system()或subprocess.check_call()传递shell命令

ner*_*com 0 python

我试图从Python调用'sed'并且通过subprocess.check_call()或os.system()传递命令行有麻烦.

我在Windows 7上,但使用Cygwin的'sed'(它在路径中).

如果我从Cygwin shell中执行此操作,它可以正常工作:

$ sed 's/&amp;nbsp;/\&nbsp;/g' <"C:foobar" >"C:foobar.temp"
Run Code Online (Sandbox Code Playgroud)

在Python中,我已经获得了我在"名称"中使用的完整路径名.我试过了:

command = r"sed 's/&amp;nbsp;/\&nbsp;/g' " +  "<" '\"' + name + '\" >' '\"' + name + '.temp' + '\"'
subprocess.check_call(command, shell=True)
Run Code Online (Sandbox Code Playgroud)

所有连接都是为了确保我在输入和输出文件名周围有双引号(如果Windows文件路径中有空格).

我也试过用以下代替最后一行:

os.system(command)
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,我都会收到此错误:

sed: -e expression #1, char 2: unterminated `s' command
'amp' is not recognized as an internal or external command,
operable program or batch file.
'nbsp' is not recognized as an internal or external command,
operable program or batch file.
Run Code Online (Sandbox Code Playgroud)

然而,正如我所说,从控制台可以正常工作.我究竟做错了什么?

Ned*_*der 5

子进程使用的shell可能不是您想要的shell.您可以使用指定shell executable='path/to/executable'.不同的shell有不同的引用规则.

更好的可能是subprocess完全跳过,并将其写为纯Python:

with open("c:foobar") as f_in:
    with open("c:foobar.temp", "w") as f_out:
        for line in f_in:
            f_out.write(line.replace('&amp;nbsp;', '&nbsp;'))
Run Code Online (Sandbox Code Playgroud)