Python单行打印当前目录中的每个文件
我怎样才能让下面的一行通过Python打印每个文件?
python -c "import sys;print '>>',sys.argv[1:]" | dir *.*
特别想知道如何通过管道输入 python -c。 接受 DOS 或 Cygwin 响应。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您想应用一些像问题中那样的格式,
如果您想使用管道,请使用
xargs
:或反引号:
If you want to apply some formatting like you have in your question,
If you want to use a pipe, use
xargs
:or backticks:
您可以通过读取 sys.stdin 来读取通过管道传输到 Python 脚本中的数据。 例如:
还不完全清楚你想做什么(也许我很愚蠢)。 混乱来自于您的示例,该示例将数据从 python 脚本中导出。
You can read data piped into a Python script by reading sys.stdin. For example:
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.
如果您想打印所有文件:
如果您只想打印当前目录的文件
如果您想包含“>>” 每行之前
如果您不希望“>>”之间有空格 和来自 echo 的 $path
当然,这都是使用 cygwin 的。
If you want to print all files:
If you want to print only the current directory's files
If you want to include the ">>" before each line
If you don't want the space between ">>" and $path from echo
This is all using cygwin, of course.
只需像正常管道一样读取标准输入
just read stdin as normal for pipes
您的管道方向错误,如果您想将“dir”的输出输入Python,“dir”必须位于左侧。 例如:(
列表理解的 hack 是因为不允许在分号后的一行上引入块“for”语句。)
显然,Python 原生解决方案(“os.listdir”)在以下方面要好得多实践。
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.:
(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.
请参阅 cobbal 的答案
通过程序进行管道传输对于从程序的角度来看,程序只知道它正在从标准输入流获取输入
一般来说,这种形式的 shell 命令
会将 A 的输出重定向为 B 的输入,
因此如果 A 将“asdf”吐出到标准输出,然后 B 将“asdf”获取到其标准输入中
python 中的标准输入流为 <代码>sys.stdin
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
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