{Python}OSコマンド実行

 

https://office54.net/python/basic/python-windows-command#section4-1


OS: Windows10
バージョン: 3.7.9

想定シナリオ:
ファイルからコマンドを取得して実行し、結果をファイルに書き込む


import subprocess

# テスト用ファイル作成

with open('a.txt', mode='w', encoding='utf-8', newline='\n') as f1:
  f1.write( 'mysql -uroot -p"password" -D test --skip-column-names -e "select now();"'+'\n' )
  f1.write( 'mysql -uroot -p"password" -D test --skip-column-names -e "show tables;"'+'\n' )
  f1.write( 'mysql -uroot -p"password" -D test --skip-column-names -e "show create table tab1 \G"'+'\n' )


# OSコマンド実行

f2 = open('b.txt', mode='w', encoding='utf-8', newline='\n')


with open('a.txt', mode='r', encoding='utf-8') as f3:
  while True:
    l = f3.readline()
    try:
      stdout = subprocess.run(l, shell=True, stdout=subprocess.PIPE).stdout
      f2.write( stdout.decode()+'\n' )
    except:
      print('失敗')
    if not l:
      break

f2.close()