Boxuan
Boxuan

Reputation: 5167

Python pass tab "\t" as argument

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?

Upvotes: 3

Views: 4749

Answers (3)

bigonazzi
bigonazzi

Reputation: 834

If you make sure your argument is always quoted, "\t", you could use:

ast.literal_eval(in_part)

Upvotes: -1

dawg
dawg

Reputation: 104042

You have two issues here.

First is that is that the \t is only functional in a Python script - you need the literal tab character in the command line.

Second is how to enter a literal tab on the command line

You enter command $'\t'

So try this:

#!/usr/bin/python

import sys
in_part = sys.argv[1]
if __name__ == "__main__":
    print 'cmd[1]={}'.format(in_part)
    print in_part == "\t"

And for the command line:

tab.py $'\t'

Upvotes: 1

pts
pts

Reputation: 87341

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')

Upvotes: 5

Related Questions