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

How can I pipe data out from python output in terminal?

我使用 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 {} \;