Skip to main content
 首页 » 编程设计

Python 将选项卡 "\t"作为参数传递

2024年11月01日898°冷暖

我有以下名为 test.py 的 Python 脚本。目标是让 Python 识别制表符。我应该怎么做?

import sys 
input = sys.argv[1] 
if __name__ == "__main__": 
    print input == "\t" 

当我将 python test.py "\t" 传递给命令行时,为什么我会得到一个 False?


[更新]

我根据下面的前两条评论更改了代码:

import sys 
someArgs = sys.argv[1] 
if __name__ == "__main__": 
    print someArgs 
    print someArgs == '\t' 

当我通过 python test.py '\t' 时,我得到了

\t 
False 

[更新 2]

不幸的是,我使用的是 Windows 命令提示符,而不是 *nix 系统。


[快速而肮脏的解决方案]

当 "\t" 在命令行中作为参数传递时,我可以尝试将其检测为 "\\t" 并手动将其分配给 Python 中的选项卡.例如,

import sys 
someArgs = sys.argv[1] 
if __name__ == "__main__": 
    if someArgs == "\\t": 
        pythonTab = "\t" 
        print pythonTab 

在命令行中,python test.py "\t" 将生成一个选项卡作为输出。谁有更优雅的解决方案?

请您参考如下方法:

反斜杠在 Python 和命令行中都有特殊含义。

您想检测单个制表符吗?那么你就正确地比较了它:input == "\t" 是正确的。但是在命令行中传递制表符是系统相关的。我不知道如何在 Windows 上执行此操作。在带有 Bash 的 Unix 上,命令行应如下所示:

python test.py $'\t' 

或

python test.py $'\011' 

在此处查看有关 Bash 中的 $' 语法的更多信息:http://www.gnu.org/software/bash/manual/bashref.html#ANSI_002dC-Quoting


您想检测两个字符:一个反斜杠和一个 t?那么你应该将它比较为:input == "\\t" 或 input == r"\t"。我不知道如何在 Windows 的命令行中传递反斜杠。在带有 Bash 的 Unix 上,命令行应如下所示:

python test.py '\t' 

在此处查看有关 Bash 中的 ' 语法的更多信息:http://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes

我建议将以下调试信息生成添加到您的程序中:

print repr(argv[1]) 
print argv[1].encode('hex')