Sorry I'm not an expert in python. Could someone explain me the behavior of the following code:
import sys
def send_cmd():
param = r'--password="some\"pass"'
print >> sys.stdout, param
cmd = [
'--adminName', 'admin',
param,
'--host', '127.0.0.1',
]
print >> sys.stdout, cmd
if __name__ == "__main__":
send_cmd()
The output that I get is the following:
--password="some\"pass"
['--adminName', 'admin', '--password="some\\"pass"', '--host', '127.0.0.1']
So when I assign raw value to the variable I get a single backslash, but when I put this var to array, it converts string to have double backslashes. But I would want to keep the value as it is - raw with a single backslash. How can I achieve this?
Thanks.
UPD:
The actual issue happens when I try to get password value in Java application. Python passes cmd to java in the form:
jar javaApp --adminName admin --password="some\\"pass"--host 127.0.0.1
And inside java application I use org.apache.commons.cli.CommandLine.getOptionValue("--password") Which returns me "some(double backslash)"pass" and that java cannot escape double quote
UPD2:
Ok, so it turns out that python is not an issue actually. The problem is that CommandLineParser (LenientPosixParser) cannot correctly parse argument passed with escape character. So when I pass to command line:
--password "some\"pass"
CommandLineParser returns "some"pass" value without trimming surrounding quotes and is not escaping double quote char.
CodePudding user response:
Python does not keep track if the string was initially defined with the r
prefix.
The value is always the same, it is just a matter of the representation when you print the value.
Compare:
>>> param = r'--password="some\"pass"'
>>> param
'--password="some\\"pass"'
>>> print(param)
--password="some\"pass"
>>> print(repr(param))
'--password="some\\"pass"'
>>> param == r'--password="some\"pass"'
True
>>> param == '--password="some\\"pass"'
True
CodePudding user response:
I don't know why it does this but you can do it using for loop iterate through cmd and output each string
for i in cmd:
sys.stdout.write(i ' ')