Skip to content

Instantly share code, notes, and snippets.

@s-note
Last active August 21, 2018 14:56
Show Gist options
  • Save s-note/35331c3972a847e0ba9e2e6ffbe62dae to your computer and use it in GitHub Desktop.
Save s-note/35331c3972a847e0ba9e2e6ffbe62dae to your computer and use it in GitHub Desktop.
pywinautoでメモ帳を起動(接続)してテキストを入力し、保存先を指定して名前を付けて保存し終了
# -*- coding: utf-8 -*-
def app_start1(app1,path1,t1):#アプリの起動および接続
import time
try:
app1.Connect(path = path1)
except:
app1.Start(cmd_line = path1)
time.sleep(t1)
app1.Connect(path = path1)
def writenotepad1(app2,text1):#メモ帳に1行書く(追記形式)
#テキストの入力
text2 = app2.Notepad.Edit1.TextBlock() #全行の入力済テキスト取得
app2.Notepad.Edit1.SetText(text1 , pos_end=text2) #次行の追記
app2.Notepad.Edit1.TypeKeys("{ENTER}") #改行
def notepadsaveas1(path2,filename2,buf2):#メモ帳を起動して書き込み名前を付けて保存し終了
import os
import time
from pywinauto.application import Application
#メモ帳の起動または接続
app = Application()
path1 = u"C:\Windows\\notepad.exe"
t1 = 2
app_start1(app,path1,t1)
#テキストを書き込み
num1 = len(buf2)
for i in range(0, num1):
writenotepad1(app,buf2[i])
#名前を付けて保存ダイアログの起動
dialog = app[u".*名前を付けて保存.*"]
if dialog.Exists() == False:
pwin = app.window_(title_re = ".*メモ帳.*")
pwin.MenuSelect("ファイル->名前を付けて保存")
buf1 = os.path.isdir(path2) #指定パスにフォルダがあるか確認
if buf1 == False:
os.mkdir(path2) #フォルダが無い場合は作成
# ファイル名を設定
filename2 = path2 + "\\" + filename2
dialog.Edit1.SetText(filename2)
time.sleep(1)
# 保存ボタンの定義
dialog_button1 = dialog[u'保存(&S)']
# 同名のファイルが存在した場合(上書きする)の「はい」ボタンの定義
confirm = app[u".*名前を付けて保存の確認"]
confirm_button1 = confirm[u'はい(&Y)']
dialog_button1.Click() #保存する
time.sleep(0.5)
if dialog_button1.Exists():
if confirm_button1.Exists() == False:
dialog_button1.Click() #上手く押せなかったら再度クリック
time.sleep(0.5)
if confirm_button1.Exists():
confirm_button1.Click() #上書きする
time.sleep(0.5)
for i in range(0, 5):
if confirm_button1.Exists():
confirm_button1.Click() #上手く押せなかったら再度クリック
time.sleep(0.5)
else:
break
pwin = app.window_(title_re = ".*メモ帳.*")
pwin.MenuSelect("ファイル->メモ帳の終了")
if __name__ == "__main__":
import os
from datetime import datetime as dt
filename01 = u"test01.txt" #ファイル名
#保存先フォルダのパスを直接指定する場合(フォルダが無い場合は自動作成)
#path01 = u'C:\\WinPython-64bit-3.4.3.6\\document\\test6_1_5_notepad'
#保存先フォルダのパスをスクリプトファイルのフォルダと同じにする場合
path01 = os.path.abspath(os.path.dirname(__file__))
#書き込むテキスト(リスト配列で渡す)
text01 = []
text01.insert(0,"テスト1")
text01.insert(1,"テスト2")
text01.insert(2,"テスト3")
tdatetime = dt.now()
tstr = tdatetime.strftime('%Y/%m/%d %H:%M:%S')
text01.insert(3,tstr)
#フォルダのパス、ファイル名、書き込むテキストを指定して
#メモ帳を起動→書き込み→保存先を指定して名前を付けて保存→メモ帳を終了
notepadsaveas1(path01,filename01,text01)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment