簡體   English   中英

如何讀取從 python 執行的 mysql 命令的錯誤內容輸出

[英]How can I read the error content outputs of mysql command executed from python

bash_fc = rf"mysql -u {source_user_name} -h {source_ipv4_addr} --password={source_db_password}"

當我對上述命令使用以下功能時,

from subprocess import PIPE,run
def cons_r(cmd):
  response = run(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
  return response.stdout
response = os.popen(bash_fc)

mysql:[警告] 在命令行界面上使用密碼可能不安全。 mysql:未知的操作系統字符集“cp857”。 mysql:切換到默認字符集“utf8mb4”。 錯誤 1045 (28000): 用戶 'root'@'pc.mshome.net' 的訪問被拒絕(使用密碼:是)

我無法讀取 output,有沒有你知道的方法讓我可以讀取它?

此更改解決了問題

from subprocess import PIPE, run, STDOUT
def cons_r(cmd):
  response = run(cmd, stdout=PIPE, stderr=STDOUT, universal_newlines=True, shell=True)
  return response.stdout

您可以從標准錯誤中讀取錯誤

import subprocess as sp

ret = sp.run(['ls', '*.bad'], stderr=sp.PIPE,
             stdout=sp.PIPE, shell=True, encoding="cp857")

if ret.returncode == 0:
    print(ret.stdout)
else:
    print(ret.stderr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM