child.stdout.read()
from subprocess import Popen
import subprocess as sp
with open("test.txt", "r") as file:
child=Popen(['python', 'child.py'], stdin=file, stdout=sp.PIPE)
s=' '
while s:
s=child.stdout.read()
print (s.rstrip().decode(errors='ignore'))
print(input(), '- all is good')
time.sleep(1)
print(input(), '- all is good')
time.sleep(1)
print(input(), '- all is good')
time.sleep(1)
hello1
hello2
hello3
hello1 - all is good
hello2 - all is good
hello3 - all is good
child.stdout.read()
. sys.stdout.flush()
, а в родительском заменить child.stdout.read()
на child.stdout.readline()
from subprocess import Popen
import subprocess as sp
with open("test.txt", "r") as file:
child=Popen(['python', 'child.py'], stdin=file, stdout=sp.PIPE)
s=' '
while s:
s=child.stdout.readline()
print (s.rstrip().decode(errors='ignore'))
print(input(), '- all is good')
time.sleep(1); sys.stdout.flush()
print(input(), '- all is good')
time.sleep(1); sys.stdout.flush()
print(input(), '- all is good')
time.sleep(1); sys.stdout.flush()
sys.stdout.flush()
может не быть. Поэтому вывод будет доступен только по завершению дочернего процесса. В таком случае замена инструкции child.stdout.read()
на child.stdout.readline()
в родительском процессе ничего не даст, цикл в коде позволит вам прочитать построчно весь вывод. Но по времени этот вывод, естественно, будет не синхронизирован с тем, когда эти строки генерировал дочерний процесс with open (r"C:\Users\user_name\Desktop\Telegram.lnk", "rb") as file:
source=file.read()
source = base64.b64encode(source)
source
source=b'TAAAAAEUAgAAAAAAwA...........AAAAAAAAAA'
source = base64.b64decode(source)
with open (r"C:\Users\user_name\Desktop\Telegram.lnk", "wb") as file:
file.write(source)
df["start_date"]=[k+" "+str(l) for k,l in list(zip(df.index.month_name(locale='ru_RU.UTF-8'),df.index.year))]
df=df.set_index("start_date")
import locale
locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')
...
ticktext=[datetime.strptime(elem, "%Y-%m-%d").strftime('%d-%b-%Y %a')
for elem in df.index]
fig.update_xaxes(tickformat='%d-%b-%Y %a')
fig.update_xaxes(tickvals=df.index)
fig.update_xaxes(ticktext=ticktext)
if array.name[-5:]=='DATES':
width=20*60*60*1000
if array.name[-4:]=='WEEK':
width=6*24*60*60*1000
if array.name[-5:]=='MONTH':
width=0.9
....
fig.add_trace(go.Bar(x=array.index, y=data, marker_color='blue', name='',
width=[width]*len(array), showlegend=False))
pub_sorted=sorted(publist.items(),
key=lambda elem: datetime.strptime(elem[1]["date"], "%d.%m.%Y %H:%M:%S"),
reverse=True)
И судя по данным реально сортирует, но данные в итоге не в виде словаря, [(key, dict-value), (key, dict-value)
(key, dict-value)]
import pandas as pd
lst=[{'id': 2785280, 'score': 13},
{'id': 66560002, 'score': 4},
{'id': 180432899, 'score': 7},
{'id': 52793348, 'score': 5},
{'id': 86411270, 'score': 5},
{'id': 2334728, 'score': 2},
{'id': 2523146, 'score': 4},
{'id': 159318028, 'score': 5},
]
df=pd.DataFrame(lst)
df=df.groupby('id')['score'].sum()
SESSION_REPORT=[]
# ЧИТАЕМ ФАЙЛЫ SESSION REPORT В PYTHON-СЛОВАРЬ #
for SESSION_REPORT_FILE in os.listdir(SESSION_REPORT_PATH):
with open(SESSION_REPORT_PATH+SESSION_REPORT_FILE, "r", newline="",
encoding="utf-8") as file:
start_date=datetime.strptime(SESSION_REPORT_FILE[14:len(SESSION_REPORT_FILE)-4], '%Y-%m-%d')
reader = csv.reader(file, delimiter = ';')
for line in reader:
if line[2]=="Длина текста": continue
start_time=datetime.combine(start_date.date(),
datetime.strptime(line[1], '%H:%M:%S').time())
voice_length=datetime.combine(start_date.date(),
datetime.strptime(line[3], '%H:%M:%S').time())-start_date
SESSION_REPORT.append({"v2m_guid": line[0], "start_date": start_date,
"start_time": start_time,
"voice_length": voice_length,
"end_time": start_time+voice_length,
"text_length": int(line[2])})
# СОЗДАЕМ DATAFRAME PANDAS #
SESSION_REPORT=pd.DataFrame(SESSION_REPORT)
IndexError: too many indices for array
сбивает с толкуarr=np.array([tpl], dtype=dt)
arr=np.array(tpl, dtype=dt)
В первом случае элементы доступны через индекс arr[0]["v2m_guid"]
arr["v2m_guid"]
from math import gcd
def uniqueFactor(lst):
if len(set(lst)) != 3:
return False
lch=[]
for num in lst:
i=0; pr=prime[i]
while gcd(num,pr) != pr:
i+=1
pr=prime[i]
lch.append(pr)
if len(set(lch)) != 3:
return False
return True
В моём случае prime это список простых чисел в Вашем может быть обыкновенный range(X) thread = Thread(target=task(*args,**kwargs), daemon=True)
thread.setDaemon(True/False)
thread.isDaemon()
wizard=app['7-Zip 19.00 (x64) Setup']
wizard.Install.Click()
time.sleep(5)
wizard.CloseButton.Click()
time.sleep(2)
app=pywinauto.Application().start(r'C:\Program Files\7-Zip\7zFM.exe')
main=app['7-Zip']
main.MenuSelect('Сервис->Настройки...')
settings=app['Настройки']
settings.Button.Click()
settings.ОКButton.Click()
main.Close()
import pywinauto, datetime, threading, time
pid_list=[]; log_list=[]
with open("kill-notepad.log", "a") as log:
log.write(f"{datetime.datetime.now()} | service started, I'am kill all notepad appliction\n")
def logger():
global log_list
if len(log_list)>0:
log_copy=log_list.copy(); log_list=[]
with open("kill-notepad.log", "a") as log:
for i in range(len(log_copy)):
log.write(log_copy.pop(0))
def disabler(main,count):
for i in range(count-count//255):
main.set_transparency(alpha=255-i//(count//255))
def alarm(main):
for i in range(10):
main.Edit.send_keystrokes("НЕЛЬЗЯ ЗАПУСКАТЬ ЭТУ ПРОГРАММУ\n")
def killer():
global pid_list
try:
app=pywinauto.Application().connect(path=r"c:\windows\system32\notepad.exe")
main=app.top_window(); count=10000
if main.process_id() not in pid_list:
pid_list.append(main.process_id())
else:
return
main.set_transparency(alpha=255)
threading.Thread(target=alarm(main)).start()
threading.Thread(target=disabler(main,count)).start()
log_list.append(f'{datetime.datetime.now()} | destroy {main.element_info}\n')
app.kill()
except:
pass
count=0
while True:
if count==10:count=0
time.sleep(1); count+=1
shout=threading.Thread(target=killer)
shout.start()
if count==10:
report=threading.Thread(target=logger)
report.start()
from cx_Freeze import setup, Executable
packages = ['win32serviceutil','win32service','win32event','servicemanager','socket','win32timezone','pywinauto', 'sys', 'datetime', 'not-notepad-service']
build_exe_options = {"packages": packages}
executable = [Executable("not-notepad-service.py")]
setup(name = "StopNotepadService",
version = "1.0",
description = "Stop NotepadApp and Log",
options = {"build_exe": build_exe_options},
executables = executable)