如何从终端的 python 输出中输出数据?

问题描述

我使用 os.listdir 获取文件夹列表..

python -c "import os; print os.listdir(os.getcwd())"

我想将输出通过管道传输到 shell 中的 for 循环并在 tcsh shell 中迭代以运行不同的命令,每个文件夹都可以在迭代中使用。

publishContent -dir "each dir name"

其中每个目录名称都是上面python的输出..

我以前也这样试过

for dirName in `python -c "import os; print os.listdir(os.getcwd())"` do publishConent -dir dirName  End

但它似乎不起作用...

解决方法

(t)csh 没有 for 循环,但它有 foreach

   foreach name (wordlist)
   ...
   end     Successively sets the variable name to each member of wordlist
           and executes the sequence of commands between this command and
           the matching end.  (Both foreach and end must appear alone on
           separate lines.)  The builtin command continue may be used to
           continue the loop prematurely and the builtin command break to
           terminate it prematurely.  When this command is read from the
           terminal,the loop is read once prompting with `foreach? ' (or
           prompt2) before any statements in the loop are executed.  If
           you make a mistake typing in a loop at the terminal you can rub
           it out.

所以你想要这样的东西:

% foreach dirName ( `python -c "import os; print(os.listdir(os.getcwd()))"` )
foreach? echo "$dirName"
foreach? end

哪个会给:

['file','file
space','file2']

据我所知,没有任何方法可以将其放在一行中。上面的文档引用提到“foreach 和 end 必须单独出现在单独的行上”。

我不知道你为什么在这里使用 Python:

% foreach dirName ( ./* )
foreach? echo "$dirName"
foreach? end
./file
./file space
./file2

它没有 Python 语法,可以正确处理带空格的文件名。

两者都会顺便列出所有文件和目录;使用 if ( -d "$dirName" ) 测试它是否是目录。

最好也使用 find

% find . -maxdepth 1 -a -type d -exec publishContent -dir {} \;