我正在运行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']
答案 0 :(得分:1)
您可以使用列表理解:
db_list = str(out.stdout).split(' ')
db_list = [x.replace("\\n", '') for x in db_list if x!= "b'" ]
答案 1 :(得分:1)
您需要解码字符串:
print(out.stdout.decode("utf-8"))
答案 2 :(得分:1)
b'...'
是bytes literal。使它成为str
decode 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']