【问题标题】:reformat output from subprocess.run()重新格式化 subprocess.run() 的输出
【发布时间】:2019-07-16 16:27:01
【问题描述】:

我正在运行 python 3.5。从终端捕获输出后,它在我的 Python IDE 中看起来略有不同。它有我不需要的其他字符,即“\n”或“b”。我尝试使用 split() 和 replace() 但没有任何效果。我究竟做错了什么?

def runIndexTest(zone):

    print('Turning OFF flit on ' + zone)
    #setIndexStatus(zone, 'stop')

    cmd1 = 'psql -h ' + zone + ' -U filmlight -t -c ' + '"' + """SELECT datname FROM pg_database WHERE datistemplate = false AND datname LIKE """ + "'fsdb%'" + ';"'
    #print(cmd1)

    out = subprocess.run(cmd1, shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    print(out.stdout)

    db_list = str(out.stdout).split(' ')
    for db in db_list:
        db = db.replace("\n", '')
        if db == "b'":
            db_list.remove(db)
            continue

    print('Length of db_list:', len(db_list))
    print(db_list)

输出:

b' fsdb\n fsdb1\n fsdb_fetish_images$v1\n fsdb_fetish_images\n fsdb_fetish_images$v2\n\n'
Length of db_list: 5
['fsdb\\n', 'fsdb1\\n', 'fsdb_fetish_images$v1\\n', 'fsdb_fetish_images\\n', "fsdb_fetish_images$v2\\n\\n'"]

期望的输出:

['fsdb', 'fsdb1', 'fsdb_fetish_images$v1', 'fsdb_fetish_images', 'fsdb_fetish_images$v2']

【问题讨论】:

标签: python subprocess output


【解决方案1】:

你需要解码字符串:

print(out.stdout.decode("utf-8"))

【讨论】:

    【解决方案2】:

    您可以使用列表推导:

    db_list = str(out.stdout).split(' ')
    db_list = [x.replace("\\n", '') for x in db_list if x!= "b'" ]
    

    【讨论】:

      【解决方案3】:

      b'...'bytes literal。使其成为strdecode it'\n' 是换行符,它们是空格,使用 str.split() with the default argument (whitespace)

      In [9]: s
      Out[9]: b' fsdb\n fsdb1\n fsdb_fetish_images$v1\n fsdb_fetish_images\n fsdb_fetish_images$v2\n\n'
      
      In [10]: s.decode('utf-8')
      Out[10]: ' fsdb\n fsdb1\n fsdb_fetish_images$v1\n fsdb_fetish_images\n fsdb_fetish_images$v2\n\n'
      
      In [11]: s.decode('utf-8').split()
      Out[11]: 
      ['fsdb',
       'fsdb1',
       'fsdb_fetish_images$v1',
       'fsdb_fetish_images',
       'fsdb_fetish_images$v2']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        • 2018-04-13
        • 1970-01-01
        • 2016-10-07
        • 2015-08-20
        相关资源
        最近更新 更多