首页 > 解决方案 > Python:获取通过管道传输到标准输入的文件名

问题描述

我有一个 python 程序,它从 stdin 读取输入(必需),并处理来自 stdin 的行:

for lines in stdin:
     #do stuff to lines
     filename = #need file name
     #example print
     print(filename)

但是,在这个 for 循环中,我还需要像这样获取已通过管道传输到这个 python 程序的文件的名称:

cat document.txt | pythonFile.py #should print document.txt with the example print

有没有办法做到这一点?

标签: pythonfilenamesstdin

解决方案


不,这是不可能的。作为管道的接收端,您不知道数据流的来源。使用cat进一步混淆它,但即使你会写./pythonFile.py < document.txt你也不知道。

许多 unix 工具接受文件名作为参数和-“stdin”的特殊代码。你可以用同样的方式设计你的脚本,所以它可以被称为

  • cat document.txt | pythonFile.py - (您的脚本不知道输入来源)
  • ./pythonFile.py document.txt(您的脚本确实知道该文件)

推荐阅读