Python:获取通过管道传输到stdin的文件名
我有一个python程序,它从stdin读取输入(必需),并处理stdin中的行:Python:获取通过管道传输到stdin的文件名,python,filenames,stdin,Python,Filenames,Stdin,我有一个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 pr
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
,您也不会有任何线索
许多unix工具接受文件名作为参数,-
作为“stdin”的特殊代码。你可以用同样的方法设计你的脚本,这样它就可以像
(您的脚本不知道输入源)cat document.txt | pythonFile.py-
(您的脚本确实知道该文件)/pythonFile.py document.txt
cmd
可以从/proc/self/fd/0
确定文件,但显然这是一个仅适用于Unix的解决方案。@ypnos好的,谢谢您的帮助和信息!当您可以将文档文件作为参数传递给python脚本时,您是否可以提供更多关于为什么要将文件名传递给python脚本的信息?@RushikeshGaidhani这是学校作业的一部分。说明告诉我们必须从标准输入获取输入。