0

I would like to get the sys.argv as below:

# main.py

import sys

arguments = sys.argv
print(arguments[1])
$ python main.py \\

I want: \

But this comes instead: \\

  • What shell are you using? What happens if you do "echo \\" to your shell (without the quotes, and without invoking Python)? – Tom Karzes Sep 17 '20 at 04:14
  • Doing ```echo \\``` gives me the output ```\\``` (I am using Command Prompt) –  Sep 17 '20 at 04:17
  • Ok, so your command prompt doesn't recognize \ as an escape character, and is passing \\ straight through to Python. The actual argument that Python sees is \\. So the question is, when given \\, how do you want to handle it in Python? Can you just type a single \, or does it have to be \\? It's showing you exactly what you typed. – Tom Karzes Sep 17 '20 at 04:18
  • if you want 1 then enter only 1 argument. or use a unique function on all your arguements. – sadbro Sep 17 '20 at 04:18
  • Check this post: https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python – Mike67 Sep 17 '20 at 04:22
  • Interesting, I'm using a shell that recognizes \ as an escape character (bash) and I get the same problem as the OP. For instance running `python -c "import sys; print(sys.argv)" \\` stores "\\" in argv instead of "\". But running `python -c "import sys; print(sys.argv)" \` doesn't store "\" in argv, because bash treats it like a newline separator. – Michael Sep 17 '20 at 04:52
  • 1
    @Michael When you `print(sys.argv)`, you are printing a list of strings. `print` converts the list to a string by calling `str()` on it, and `str()` on lists call `repr()` on the items, so you should be seeing quotes and backslashes which aren't really there. – Ture Pålsson Sep 17 '20 at 05:16
  • @Michael Read Ture's explanation. Also, try the following: `print("\\")` vs. `print(["\\"])`. The string is the same in both cases (a single \ ), but the latter uses `repr` to show it since it's in a list, rather than being printed directly. Note that with `repr`, you also get quotes around the string, which implies that escapes will be shown. – Tom Karzes Sep 17 '20 at 05:56

0 Answers0