On 12/19/2022 9:24 PM, Jach Feng wrote:
Mark Bourne 在 2022年12月20日 星期二凌晨4:49:13 [UTC+8] 的信中寫道:
Jach Feng wrote:
I have a script using the argparse module. I want to enter the string 
"step\x0A" as one of its positional arguments. I expect this string has a 
length of 5, but it gives 8. Obviously the escape character didn't function correctly. 
How to do it?
That depends on the command-line shell you're calling your script from.

In bash, you can include a newline in a quoted string:
./your_script 'step
'
(the closing quote is on the next line)

Or if you want to do it on a single line (or use other escape
sequences), you can use e.g.:
./your_script $'step\x0a'
(dollar sign before a single-quoted string which contains escape sequences)

--
Mark.
That's really good for Linux user! How about Windows?

One way is to process the argument after it gets into Python rather than before. How hard that will be depends on how general you need the argument to be. For your actual example, the argument comes into Python as if it were

arg1 = r"step\x0A"  # or "step\\x0a"

You can see if there is an "\\x":

pos = arg1.find('\\x')  # 4

Replace or use a regex to replace it:

arg1_fixed = arg1.replace('\\x0A', '\n')

Naturally, if "\\x0A" is only a special case and other combinations are possible, you will need to figure out what you need and do some more complicated processing.

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to