2012-01-23 90 views
1

我想写一个zsh函数来获取python模块的路径。zsh函数捕获命令输出

这工作:

pywhere() { 
    python -c "import $1; print $1.__file__" 
} 

不过,我真的很喜欢的是没有文件名的目录路径。这是行不通的:

pywhere() { 
    dirname $(python -c "import $1; print $1.__file__") 
} 

注意:它在bash中工作,但不在zsh中!

编辑这是错误:

~ % pywhere() { 
function → dirname $(python -c "import $1; print $1.__file__") 
function → } 
    File "<string>", line 1 
    import pywhere() { 
       ^
SyntaxError: invalid syntax 
+0

这看起来是正确的,它适用于我。它怎么不适合你? – Gilles

+0

啊 - 只是注意到在另一个系统上工作正常。所以一定是我的zsh配置中的东西我猜..呃! – bee

+0

如果我在preexec中使用标题函数,则会发生错误: http://dotfiles.org/~_why/.zshrc 我刚刚对此进行了评论。不确定为什么这会干扰函数定义。 – bee

回答

2

你的问题是由于破preexec:你是不是引用命令行正确,当你打印它包含在窗口标题中。

.zshrc您发布,这是不是你所使用的,我看(不这样做,始终复制粘贴确切的文件内容,并命令你使用!):

a=${(V)1//\%/\%\%} 
a=$(print -Pn "%40>...>$a" | tr -d "\n") 
print -Pn "\ek$a:$3\e\\" 

print -P导致及时扩展。您在参数中包含命令。通过加倍命令来保护命令中的%角色,但这还不够。你显然有prompt_subst选项导通,从而使print -P要执行的$(…)构建体在定义该函数的命令行:

python -c "import $1; print $1.__file__" 

其中$1是命令行(函数定义:pywhere { … })。

而不是尝试解析命令行,从字面上打印出来。这也会纠正其他错误:除了没有考虑到prompt_subst之外,您还会将%的符号翻倍,但是应该将它们翻两番,因为您执行了两次提示扩展,并且还扩展了\两次。

function title() { 
    a=${(q)1} # show control characters as escape sequences 
    if [[ $#a -gt 40 ]]; then a=$a[1,37]...; fi 
    case $TERM in 
    screen) 
    print -Pn "\ek"; print -r -- $a; print -Pn ":$3\e\\";; 
    xterm*|rxvt) 
    print -Pn "\e]2;$2 | "; print -r -- $a; print -Pn ":$3\a";; 
    esac 
} 
+0

非常感谢。解决了这个问题。 – bee

1

为什么不直接使用此:

python -c "import os, $1; print os.path.dirname($1.__file__)" 
+0

不错的主意,谢谢 – bee