python-fire icon indicating copy to clipboard operation
python-fire copied to clipboard

How strings are processed in fire.

Open Scsourav18 opened this issue 7 years ago • 3 comments

I exposed a method(which takes a string as input parameter) to command line and called the method by passing "D:\test" as parameter value and below is the function body.

path=str(path).strip()
path=os.path.normpath(path)
print(path)
print(os.path.isdir(path))

Here the output is

D:\test
true

if i hardcode parameter value in the method as:

path="D:\test"
path=str(path).strip()
path=os.path.normpath(path)
print(path)
print(os.path.isdir(path))

the output is

D:       est
False

Here the "\t" is treated as special character.

Can someone please guide on this Thankyou.

Scsourav18 avatar Feb 07 '19 10:02 Scsourav18

In a standard Python string \t is the tab character. If you instead use a raw Python string r"D:\test", or if you escape the backslash "D:\\test", then you'll get the string you want D:\test.

dbieber avatar Feb 08 '19 15:02 dbieber

@dbieber Thanks for the quick response. But my initial query was passing the same string "D:\test" from command line and using same string from my code(hard coding the string) give different results. Are the strings that are passed from command line as parameter are raw strings ?

Scsourav18 avatar Feb 11 '19 06:02 Scsourav18

The shell has its own rules for parsing strings that get applied before Python is even invoked. These rules mostly applied to handling quotes. So no, the command line doesn’t use raw strings strictly speaking.

Once Fire receives the input arg from the shell, it may parse it as another type (int, bool, etc), but in your case it sees it is a string and leaves in unchanged.

When you instead pass the argument hardcoded in Python, Python treats it as a string according to python’s rules for literals before it gets passed to fire. It’s in these rules that “\t” means TAB whereas “\t” or r”\t” mean “\t”. On Mon, Feb 11, 2019 at 1:12 AM Scsourav18 [email protected] wrote:

Thanks for the quick response. But my initial query was passing the same string "D:\test" from command line and using same string from my code(hardcoding the string) give different results. Are the strings that are passed from command line as parameter are raw strings ?

— You are receiving this because you modified the open/close state.

Reply to this email directly, view it on GitHub https://github.com/google/python-fire/issues/162#issuecomment-462227586, or mute the thread https://github.com/notifications/unsubscribe-auth/AA2fXcCR7pDMgTxcCzTB2kat-w3R1neXks5vMQnlgaJpZM4anC52 .

dbieber avatar Feb 11 '19 14:02 dbieber