Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass "\t" to python from the command line? [duplicate]

Possible Duplicate:
Passing meta-characters to Python as arguments from command line

I want to pass a parameter from the command line to a python script to specify what my input file is delimited with. (e.g. "," or "\t"). For flexibility's sake, I'd like to specify it directly on the command line, not code in options for this parameter into the script.

e.g.

pythonscript.py --in_delimiter "\t" --in_file input.txt

I seem to be having problems with the backslash being interpreted before python receives it. I tried to escape this by adding extra backslashes but couldn't get it to work.

My Question: Is it possible to pass something like "\t" from the command line or do I have to use codes which I interpret inside the script (e.g. c = "," or t= "\t", etc).

Thanks for your help.

like image 327
kanne Avatar asked Jan 10 '13 05:01

kanne


People also ask

How do you pass a file path as a command line argument in Python?

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: Notice two things here: You should use forward slashes with pathlib functions. The Path() object will convert forward slashes into the correct kind of slash for the current operating system.

How do you pass a Python script command?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.


2 Answers

Are you doing it in Bash? If so, try:

pythonscript.py --in_delimiter $'\t' --in_file input.txt
like image 129
Pavel Repin Avatar answered Oct 05 '22 03:10

Pavel Repin


On unix/linux, it's easy enough to pass the tab in. You need to quote it because it's whitespace

To type the literal tab, use ctrl-v tab

pythonscript.py --in_delimiter "   " --in_file input.txt
                                 ^
                                 | this is `ctrl-v` `tab`

Alternatively you could have a mapping for special cases

pythonscript.py --in_delimiter TAB --in_file input.txt

which you deal with in the code like this

in_delimiter = {"TAB": "\t", "COMMA": ","}.get(in_delimiter, in_delimiter)
like image 25
John La Rooy Avatar answered Oct 05 '22 01:10

John La Rooy