Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pass tab "\t" as argument

Tags:

python

I have the following Python script named test.py. The goal is to let Python recognize tab. How should I do that?

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

When I pass python test.py "\t" to the command line, why do I get a False?


[Update]

I changed the code according to first two comments below:

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

When I pass python test.py '\t', I get

\t
False

[Update 2]

Unfortunately, I am using Windows command prompt, not *nix systems.


[Quick & dirty solution]

When "\t" is passed as argument in command line, I can try to detect it as "\\t" and manually assign it to tab in Python. For example,

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

From command line, python test.py "\t" will produce a tab as output. Anyone has more elegant solutions?

like image 975
Boxuan Avatar asked Jan 30 '26 03:01

Boxuan


1 Answers

Backslash has a special meaning both in Python and in the command-line.

Do you want to detect a single tab character? Then you are comparing it correctly: input == "\t" is correct. But it's system-dependent to pass a tab character in the command-line. I don't know how to do it on Windows. On Unix with Bash, the command-line should look like:

python test.py $'\t'

or

python test.py $'\011'

See more info about the $' syntax in Bash here: http://www.gnu.org/software/bash/manual/bashref.html#ANSI_002dC-Quoting


Do you want to detect two characters: a backslash and a t? Then you should compare it as: input == "\\t" or input == r"\t". I don't know how to pass a backslash in the command-line on Windows. On Unix with Bash, the command-line should look like:

python test.py '\t'

See more info about the ' syntax in Bash here: http://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes

I recommend adding the following debug info generation to your program:

print repr(argv[1])
print argv[1].encode('hex')
like image 155
pts Avatar answered Feb 01 '26 16:02

pts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!