Skip to main content
 首页 » 编程设计

python之为什么 subprocess.Popen 使用旧版本的 vim

2025年05月04日8powertoolsteam

当我运行 vi --version 时,我看到了 VIM - Vi IMproved 7.3,但是当我运行以下脚本时,它会打印出我的版本是 7.2。为什么?

路径名 是vi。 which vi 打印 /usr/local/bin/vim 并且 --version 是 7.3。 which gvim 打印 /usr/bin/gvim,--version 也打印 vim 的较新版本。

echo $EDITOR 打印 vi。

#!/usr/bin/python 
import os 
import sys 
import os.path 
import subprocess 
import tempfile 
 
 
def exec_vimcmd(commands, pathname='', error_stream=None): 
"""Run a list of Vim 'commands' and return the commands output.""" 
try: 
    perror = error_stream.write 
except AttributeError: 
    perror = sys.stderr.write 
 
if not pathname: 
    pathname = os.environ.get('EDITOR', 'gvim') 
 
args = [pathname, '-u', 'NONE', '-esX', '-c', 'set cpo&vim'] 
fd, tmpname = tempfile.mkstemp(prefix='runvimcmd', suffix='.clewn') 
commands.insert(0,  'redir! >%s' % tmpname) 
commands.append('quit') 
for cmd in commands: 
    args.extend(['-c', cmd]) 
 
output = f = None 
try: 
    try: 
        print "args are" 
        print args 
        subprocess.Popen(args).wait() 
        f = os.fdopen(fd) 
        output = f.read() 
        print "output is" 
        print output 
        print "that's the end of the output" 
    except (OSError, IOError), err: 
        if isinstance(err, OSError) and err.errno == errno.ENOENT: 
            perror("Failed to run '%s' as Vim.\n" % args[0]) 
            perror("Please set the EDITOR environment variable or run " 
                            "'pyclewn --editor=/path/to/(g)vim'.\n\n") 
        else: 
            perror("Failed to run Vim as:\n'%s'\n\n" % str(args)) 
            perror("Error; %s\n", err) 
        raise 
finally: 
    if f is not None: 
        f.close() 
 
exec_vimcmd(['version']) 

打印的参数是

['vi', '-u', 'NONE', '-esX', '-c', 'set cpo&vim', '-c', 'redir! >/var/folders/86/062qtcyx2rxbnmn8mtpkyghs0r0r_z/T/runvimcmducLQCe.clewn', '-c', 'version', '-c', 'quit'] 

请您参考如下方法:

找出分配给 pathname 的值,并查看它是否与在命令提示符下输入的 which vim 或 which gvim 一致.您的脚本正在查看您的 $EDITOR 环境变量,但是当您从命令行运行 (g)vim 时,它会搜索您的 $PATH 到找到第一个命中。例如,您可能从 CLI 运行 /opt/local/bin/vim,但从您的脚本运行 /usr/bin/vim。