【问题标题】:Assign the value of shell command line's output to a Vaiable in python将shell命令行输出的值分配给python中的变量
【发布时间】:2021-03-18 21:12:00
【问题描述】:

我有一个包含以下内容的文件。

[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 $2}'
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 $2}'", shell=True)
>>> print(output)
    b'SYSTEM\n'

我只希望它是 SYSTEM,而不是任何其他特殊字符。

【问题讨论】:

    标签: python-3.x shell variables subprocess


    【解决方案1】:

    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 文本。

    【讨论】:

      猜你喜欢
      • 2012-01-27
      • 2016-09-08
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2011-08-13
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多