Python stdin文件名 [英] Python stdin filename

查看:120
本文介绍了Python stdin文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取命令行中给定的文件名.例如:

I'm trying to get the filename thats given in the command line. For example:

python3 ritwc.py< DarkAndStormyNight.txt

python3 ritwc.py < DarkAndStormyNight.txt

我正在尝试获取DarkAndStormyNight.txt

I'm trying to get DarkAndStormyNight.txt

当我尝试fileinput.filename()时,我与sys.stdin相同.这可能吗?我不是在寻找返回当前脚本名称的sys.argv [0].

When I try fileinput.filename() I get back same with sys.stdin. Is this possible? I'm not looking for sys.argv[0] which returns the current script name.

谢谢!

推荐答案

通常,无法以与平台无关的方式获取文件名.其他答案涵盖了一些明智的选择,例如在命令行上传递名称.

In general it is not possible to obtain the filename in a platform-agnostic way. The other answers cover sensible alternatives like passing the name on the command-line.

在Linux和某些相关系统上,您可以通过以下技巧获得文件名:

On Linux, and some related systems, you can obtain the name of the file through the following trick:

import os
print(os.readlink('/proc/self/fd/0'))

/proc/是Linux上的特殊文件系统,它提供有关计算机上进程的信息. self表示当前正在运行的进程(打开文件的进程). fd是一个目录,其中包含该过程中每个打开的文件描述符的符号链接. 0是stdin的文件描述符号.

/proc/ is a special filesystem on Linux that gives information about processes on the machine. self means the current running process (the one that opens the file). fd is a directory containing symbolic links for each open file descriptor in the process. 0 is the file descriptor number for stdin.

这篇关于Python stdin文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆