通过Python os.system()或subprocess.check_call()传递shell命令

通过Python os.system()或subprocess.check_call()传递shell命令,python,Python,我试图从Python调用“sed”,但在通过subprocess.check_call()或os.system()传递命令行时遇到问题 我使用的是Windows7,但使用的是Cygwin的“sed”(在路径中) 如果我从Cygwin shell中执行此操作,它可以正常工作: $ sed 's/&amp;nbsp;/\&nbsp;/g' <"C:foobar" >"C:foobar.temp" 无论哪种方式,我都会遇到以下错误: sed: -e expression

我试图从Python调用“sed”,但在通过subprocess.check_call()或os.system()传递命令行时遇到问题

我使用的是Windows7,但使用的是Cygwin的“sed”(在路径中)

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

$ sed 's/&amp;nbsp;/\&nbsp;/g' <"C:foobar" >"C:foobar.temp"
无论哪种方式,我都会遇到以下错误:

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.

然而,正如我所说,它在控制台上工作正常。我做错了什么

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

更好的做法可能是完全跳过
子流程
,并将其作为纯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;'))

我想您会发现,在Windows Python中,它实际上并没有使用CygWin shell来运行您的命令,而是使用
cmd.exe

而且,
cmd
不能像
bash
那样使用单引号

您只需执行以下操作即可确认:

c:\pax> echo hello >hello.txt

c:\pax> type "hello.txt"
hello

c:\pax> type 'hello.txt'
The system cannot find the file specified.

我认为最好的办法是使用Python本身来处理文件。Python语言是一种跨平台的语言,旨在消除所有平台特定的不一致性,例如您刚才发现的不一致性。

我同意Ned Batcheld的观点,但是,想想你可能想用下面的代码考虑什么,因为它很可能完成你最终想要完成的事情,在Python的<代码>文件输入< /COD>模块的帮助下,可以很容易地完成:

import fileinput

f = fileinput.input('C:foobar', inplace=1)
for line in f:
    line = line.replace('&amp;nbsp;', '&nbsp;')
    print line,
f.close()
print 'done'
这将有效地更新给定的文件,正如使用关键字所建议的那样。还有一个可选的
backup=
关键字——上面没有使用——如果需要,它将保存原始文件的副本


顺便说一句,请注意使用类似
C:foobar
的东西来指定文件名,因为在Windows上,它意味着在驱动器C:上的当前目录中有一个同名文件,这可能不是您想要的。

我可以建议您完全跳过sed,然后把它写成一个四行Python脚本?你不能在iterable中使用像
这样的shell结构,因为
check\u call
只是引用它们。你必须把它们组合成一个字符串。。。。但是听内德说。。。他知道他的东西。谢谢;这只是一个例子。文件路径来自os.walk;@nerdfever.com:如果您使用
os.walk
来收集要处理的文件名,那么在Python中处理每一个文件(数百个文件)就更有意义了——这可能比使用外部程序更快、更容易。
c:\pax> echo hello >hello.txt

c:\pax> type "hello.txt"
hello

c:\pax> type 'hello.txt'
The system cannot find the file specified.
import fileinput

f = fileinput.input('C:foobar', inplace=1)
for line in f:
    line = line.replace('&amp;nbsp;', '&nbsp;')
    print line,
f.close()
print 'done'