I’m trying to write a zsh function to get the path to a python module.
This works:
pywhere() {
python -c "import $1; print $1.__file__"
}
However, what I’d really like is the dir path without the filename. This doesn’t work:
pywhere() {
dirname $(python -c "import $1; print $1.__file__")
}
Note: it works in bash, but not in zsh!
EDIT this is the error:
~ % pywhere() {
function → dirname $(python -c "import $1; print $1.__file__")
function → }
File "<string>", line 1
import pywhere() {
^
SyntaxError: invalid syntax
Your problem is due to a broken
preexec: you aren’t quoting the command line properly when you print it for inclusion in the window title.In the
.zshrcyou posted, which is not the one you used (don’t do that! Always copy-paste the exact file contents and commands that you used), I see:print -Pcauses prompt expansion. You include the command in the argument. You protect the%characters in the command by doubling them, but that’s not enough. You evidently have theprompt_substoption turned on, soprint -Pcauses the$(…)construct in the command line that defines the function to be executed:where
$1is the command line (the function definition:pywhere { … }).Rather than attempt to parse the command line, print it out literally. This’ll also correct other mistakes: beyond not taking
prompt_substinto account, you doubled%signs but should have quadrupled them since you perform prompt expansion twice, and you expand\sequences twice as well.