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.
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.
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.
Are you doing it in Bash? If so, try:
pythonscript.py --in_delimiter $'\t' --in_file input.txt
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With