Search code examples
shelltcsh

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


I get list of folders using os.listdir..

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

I want to pipe the output to a for loop in shell and iterate in tcsh shell to run a different command to which each folder can be used in iteration.

publishContent -dir "each dir name"

where each dir name is the output from python above..

I have tried like this before

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

But it didn't seem to work...


Solution

  • (t)csh doesn't have a for loop, but it does have 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.
    

    So you want something like:

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

    Which will give:

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

    There isn't any way to put this on a single line, as far as I know. And the documentation quotes above mention that "Both foreach and end must appear alone on separate lines".

    I'm not sure why you're using Python here though:

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

    Which doesn't have the Python syntax, and will handle filenames with spaces correctly.

    Both will list all files and directories by the way; use if ( -d "$dirName" ) to test if it's a directory.

    It might be better to use find as well:

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