在Python中调用subprocess.Popen时出现“系统找不到指定的文件”
我正在尝试使用 svnmerge.py
来合并一些文件。这个工具背后是用 Python 写的,但我在使用的时候遇到了一个错误——“系统找不到指定的文件”。我同事们也在用同样版本的 svnmerge.py
和 Python(具体是 2.5.2,版本号 r252:60911),但他们没有问题。
我找到了一些资料,这个链接描述了我遇到的问题。按照里面的建议,我确认了 Python 能找到 SVN(它在我的路径中):
P:\>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> i,k = os.popen4("svn --version") >>> i.close() >>> k.readline() 'svn, version 1.4.2 (r22196)\n'
不过,当我查看 svnmerge.py
的代码时,我发现对于 2.4 及更高版本的 Python,它走的是不同的执行路径。它不是调用 os.popen4(),而是使用 subprocess.Popen()。尝试这样做又出现了错误:
C:\>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess >>> p = subprocess.Popen("svn --version", stdout=subprocess.PIPE, >>> close_fds=False, stderr=subprocess.PIPE) Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\subprocess.py", line 594, in __init__ errread, errwrite) File "C:\Python25\lib\subprocess.py", line 816, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified >>>
目前,我已经把针对 2.4 及以上版本的代码注释掉了,但我想找到一个合适的解决办法。
如果这还不明显,我对 Python 完全是个新手,但谷歌也没能帮我解决这个问题。
1 个回答
23
这是一个错误,具体可以参考关于subprocess.Popen
的文档。这里需要有一个选项"shell=True
",或者第一个参数需要是一个序列,比如['svn', '--version']
。现在这样写的话,Popen
会去找一个叫“svn --version”的可执行文件,但它找不到。
不过我不明白为什么你的同事可以运行成功,如果他们用的是相同的操作系统和Python版本……顺便说一下,在我的Mac上也出现了同样的错误信息,而我给出的两种解决方法都能修复这个问题。