python - 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
有没有办法做到这一点?
解决方案
不,这是不可能的。作为管道的接收端,您不知道数据流的来源。使用cat
进一步混淆它,但即使你会写./pythonFile.py < document.txt
你也不知道。
许多 unix 工具接受文件名作为参数和-
“stdin”的特殊代码。你可以用同样的方式设计你的脚本,所以它可以被称为
cat document.txt | pythonFile.py -
(您的脚本不知道输入来源)./pythonFile.py document.txt
(您的脚本确实知道该文件)
推荐阅读
- teiid - 显式调用 TEIID 函数
- python - 当我启用 uwsgi 线程支持并启动调度程序时,api 停止工作
- node.js - 最近安装 Grpc-js 时出错,指出“node-pre-gyp install 中的错误...”?
- javascript - JS 代码在 Chrome 中完美运行,但在 Safari 中无法运行
- azure - 有没有办法在同一个 Azure 数据工厂中为管道和数据集设置不同的权限?
- python - 如何将字符串输入转换为矩阵?
- java - 如何从 Preference 中的 AlertDialog 获取值
- vb.net - 如何格式化美国货币而不在excel中的小数点后四舍五入?
- reactjs - 在 reducer 中过滤数据,然后使用来自 'react-redux' 的 { connect } 将其附加到组件;
- c# - ASP.Net Core 3.1 升级