views:

1324

answers:

6

How can I make the following one liner print every file through Python?

python -c "import sys;print '>>',sys.argv[1:]" | dir *.*

Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.

+5  A: 
python -c "import os; print os.listdir('.')"

If you want to apply some formatting like you have in your question,

python -c "import os; print '\n'.join(['>>%s' % x for x in os.listdir('.')])"

If you want to use a pipe, use xargs:

ls | xargs python -c "import sys; print '>>', sys.argv[1:]"

or backticks:

python -c "import sys; print '>>', sys.argv[1:]" `ls`
Greg Hewgill
Thanks, would like to know how to pipe though.
Luis
+4  A: 

You can read data piped into a Python script by reading sys.stdin. For example:

ls -al | python -c "import sys; print sys.stdin.readlines()"

It is not entirely clear what you want to do (maybe I am stupid). The confusion comes from your example which is piping data out of a python script.

Ali A
+4  A: 

If you want to print all files:

find . -type f

If you want to print only the current directory's files

find . -type f -maxdepth 1

If you want to include the ">>" before each line

find . -type f -maxdepth 1 | xargs -L 1 echo ">>"

If you don't want the space between ">>" and $path from echo

find . -type f -maxdepth 1 | xargs -L 1 printf ">>%s\n"

This is all using cygwin, of course.

Richard Levasseur
+1 - python is nice (I'm a fan), but sometimes there are tools just built to do the job already :-)
Jarret Hardie
+3  A: 
ls | python -c "import sys; print sys.stdin.read()"

just read stdin as normal for pipes

cobbal
true, but then what's the point?
hasen j
no point inherently, but it's a starting point for slightly more complex and possibly useful commands.
cobbal
+2  A: 

would like to know how to pipe though

You had the pipe the wrong way round, if you wanted to feed the output of ‘dir’ into Python, ‘dir’ would have to be on the left. eg.:

dir "*.*" | python -c "import sys;[sys.stdout.write('>>%s\n' % line) for line in sys.stdin]"

(The hack with the list comprehension is because you aren't allowed a block-introducing ‘for’ statement on one line after a semicolon.)

Clearly the Python-native solution (‘os.listdir’) is much better in practice.

bobince
+1  A: 

Specifically would like to know how to pipe into a python -c

see cobbal's answer

piping through a program is transparent from the program's point of view, all the program knows is that it's getting input from the standard input stream

Generally speaking, a shell command of the form

A | B

redirects the output of A to be the input of B

so if A spits "asdf" to standard output, then B gets "asdf" into its standard input

the standard input stream in python is sys.stdin

hasen j
One thing kinda bothers me though. Why do you want to use `python -c`?
hasen j
to avoid writing a py file saving it and then running though cmd line.
Luis