将 shell 命令行输出的值分配给 python 中的变量
Assign the value of shell command line's output to a Vaiable in python
我有一个包含以下内容的文件。
[oracle@hostname POST_DB_REFRESH_VALIDATIONS]$ cat .DB_Creds.txt
DEW:SYSTEM:ss2021:NPDOR
STW:SYSTEM:ss2021:NPDOR
当我 运行 在 shell 中执行以下命令时,我得到了 SYSTEM
的精确输出
[oracle@hostname POST_DB_REFRESH_VALIDATIONS]$ grep DEW .DB_Creds.txt | awk -F':' '{print }'
SYSTEM
而当我 运行 在 python3 命令行中使用 subprocess
相同时,我得到如下输出。
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 }'", shell=True)
>>> print(output)
b'SYSTEM\n'
我只希望它作为 SYSTEM,而不是任何其他特殊字符。
output
的类型为 bytes
。您希望首先将其解码为 str
类型的值,然后去除尾随的换行符。
>>> print(output.decode().strip())
SYSTEM
您可以观察方法调用产生的差异:
>>> output
b'SYSTEM\n'
>>> output.decode()
'SYSTEM\n'
>>> output.decode().strip()
'SYSTEM'
默认情况下,decode
将 bytes
值视为字符串的 UTF-8 编码,但该假设是有效的,因为您有纯 ASCII 文本。
我有一个包含以下内容的文件。
[oracle@hostname POST_DB_REFRESH_VALIDATIONS]$ cat .DB_Creds.txt
DEW:SYSTEM:ss2021:NPDOR
STW:SYSTEM:ss2021:NPDOR
当我 运行 在 shell 中执行以下命令时,我得到了 SYSTEM
的精确输出[oracle@hostname POST_DB_REFRESH_VALIDATIONS]$ grep DEW .DB_Creds.txt | awk -F':' '{print }'
SYSTEM
而当我 运行 在 python3 命令行中使用 subprocess
相同时,我得到如下输出。
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 }'", shell=True)
>>> print(output)
b'SYSTEM\n'
我只希望它作为 SYSTEM,而不是任何其他特殊字符。
output
的类型为 bytes
。您希望首先将其解码为 str
类型的值,然后去除尾随的换行符。
>>> print(output.decode().strip())
SYSTEM
您可以观察方法调用产生的差异:
>>> output
b'SYSTEM\n'
>>> output.decode()
'SYSTEM\n'
>>> output.decode().strip()
'SYSTEM'
默认情况下,decode
将 bytes
值视为字符串的 UTF-8 编码,但该假设是有效的,因为您有纯 ASCII 文本。