Reputation: 149
I have a file with the below contents.
[oracle@hostname POST_DB_REFRESH_VALIDATIONS]$ cat .DB_Creds.txt
DEW:SYSTEM:ss2021:NPDOR
STW:SYSTEM:ss2021:NPDOR
When i run the below command in shell I am getting exact output as SYSTEM
[oracle@hostname POST_DB_REFRESH_VALIDATIONS]$ grep DEW .DB_Creds.txt | awk -F':' '{print $2}'
SYSTEM
whereas when i run the same in python3 command line using subprocess
, i am getting the output as below.
Python 3.6.8 (default, Sep 26 2019, 11:57:09)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> output = subprocess.check_output("grep DEW .DB_Creds.txt | awk '{print $2}'", shell=True)
>>> print(output)
b'SYSTEM\n'
I just want it as SYSTEM, not with any other special characters.
Upvotes: 0
Views: 16
Reputation: 530823
output
has type bytes
. You want to first decode that to a value of type str
, then strip the trailing newline.
>>> print(output.decode().strip())
SYSTEM
You can observe the differences made by the method calls:
>>> output
b'SYSTEM\n'
>>> output.decode()
'SYSTEM\n'
>>> output.decode().strip()
'SYSTEM'
decode
treats the bytes
value as the UTF-8 encoding of a string by default, but that assumption is valid since you have plain ASCII text.
Upvotes: 1