import ctypes
import sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
# Код, который требует прав администратора
print("Программа запущена с правами администратора")
input("Нажмите Enter для завершения программы...")
else:
# Перезапускаем программу с запросом прав администратора
ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1
)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
import time
import ctypes
import win32con
from ctypes import wintypes as w
KEYEVENTF_SCANCODE = 0x8
KEYEVENTF_UNICODE = 0x4
KEYEVENTF_KEYUP = 0x2
SPACE = 0x39
INPUT_KEYBOARD = 1
# not defined by wintypes
ULONG_PTR = ctypes.c_ulong if ctypes.sizeof(
ctypes.c_void_p) == 4 else ctypes.c_ulonglong
class KEYBDINPUT(ctypes.Structure):
_fields_ = [('wVk', w.WORD),
('wScan', w.WORD),
('dwFlags', w.DWORD),
('time', w.DWORD),
('dwExtraInfo', ULONG_PTR)]
class MOUSEINPUT(ctypes.Structure):
_fields_ = [('dx', w.LONG),
('dy', w.LONG),
('mouseData', w.DWORD),
('dwFlags', w.DWORD),
('time', w.DWORD),
('dwExtraInfo', ULONG_PTR)]
class HARDWAREINPUT(ctypes.Structure):
_fields_ = [('uMsg', w.DWORD),
('wParamL', w.WORD),
('wParamH', w.WORD)]
class DUMMYUNIONNAME(ctypes.Union):
_fields_ = [('mi', MOUSEINPUT),
('ki', KEYBDINPUT),
('hi', HARDWAREINPUT)]
class INPUT(ctypes.Structure):
_anonymous_ = ['u']
_fields_ = [('type', w.DWORD),
('u', DUMMYUNIONNAME)]
lib = ctypes.WinDLL('user32')
lib.SendInput.argtypes = w.UINT, ctypes.POINTER(INPUT), ctypes.c_int
lib.SendInput.restype = w.UINT
def send_scancode(code):
i = INPUT()
i.type = INPUT_KEYBOARD
i.ki = KEYBDINPUT(0, code, KEYEVENTF_SCANCODE, 0, 0)
lib.SendInput(1, ctypes.byref(i), ctypes.sizeof(INPUT))
i.ki.dwFlags |= KEYEVENTF_KEYUP
lib.SendInput(1, ctypes.byref(i), ctypes.sizeof(INPUT))
def send_unicode(s):
i = INPUT()
i.type = INPUT_KEYBOARD
for c in s:
i.ki = KEYBDINPUT(0, ord(c), KEYEVENTF_UNICODE, 0, 0)
lib.SendInput(1, ctypes.byref(i), ctypes.sizeof(INPUT))
i.ki.dwFlags |= KEYEVENTF_KEYUP
lib.SendInput(1, ctypes.byref(i), ctypes.sizeof(INPUT))
def find_notepad_window(notepad_title):
while True:
notepad_handle = ctypes.windll.user32.FindWindowW(None, notepad_title)
if notepad_handle != 0:
return notepad_handle
time.sleep(1)
def insert_text_into_notepad(notepad_handle, text):
# Развернуть окно, если оно свернуто
ctypes.windll.user32.ShowWindow(notepad_handle, win32con.SW_RESTORE)
# Сделать окно активным
ctypes.windll.user32.SetForegroundWindow(notepad_handle)
# Изменить заголовок окна
# ctypes.windll.user32.SendMessageW(notepad_handle, win32con.WM_SETTEXT, 0, text)
# send_scancode(SPACE)
# Текст в блокнот
send_unicode(text)
if __name__ == "__main__":
notepad_title = "Безымянный – Блокнот"
text_to_insert = "Привет, мир!"
notepad_handle = find_notepad_window(notepad_title)
insert_text_into_notepad(notepad_handle, text_to_insert)
import ctypes
def enum_windows_callback(hwnd, lParam):
window_title = ctypes.create_unicode_buffer(1024)
ctypes.windll.user32.GetWindowTextW(hwnd, window_title, 1024)
print(f"Window Handle: {hwnd}, Window Title: {window_title.value}")
return True
ctypes.windll.user32.EnumWindows(ctypes.WINFUNCTYPE(
ctypes.c_bool, ctypes.c_ulong, ctypes.c_ulong)(enum_windows_callback), 0)
arr = [
['t', 'e', 'k', 's', 't'],
['d', 'l', 'y', 'a'],
['p', 'r', 'i', 'm', 'e', 'r', 'a']
]
for i in arr:
# получаем вложенные списки
print(f'В списке {i}: Такие элементы: ', end='')
for j in i:
# выводим каждый элемент
print(f'{j}, ', end='')
print()
import disnake
from disnake.ext import commands
from youtube_dl import YoutubeDL
YDL_OPTIONS = {'format': 'worstaudio/best', 'noplaylist': 'False', 'simulate': 'True', 'key': 'FFmpegExtractAudio'}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
class Play(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def play(self, ctx, url):
vc = await ctx.author.voice.channel.connect()
with YoutubeDL(YDL_OPTIONS) as ydl:
if 'https://' in url:
info = ydl.extract_info(url, download=False)
else:
info = ydl.extract_info(f"ytsearch:{url}", download=False)['entries'][0]
link = info['formats'][0]['url']
vc.play(disnake.FFmpegPCMAudio(executable="ffmpeg\\ffmpeg.exe", source=link, **FFMPEG_OPTIONS))
def setup(bot):
bot.add_cog(Play(bot))
from sys import stdout
from time import sleep
PAUSE = 1
START_STEP = -15
END_STEP = 15
for sec in range(START_STEP, END_STEP):
if sec == START_STEP:
stdout.write(f'Timer: {sec}')
else:
for _ in range(len(str(prev_sec))):
stdout.write('\033[D \033[D')
stdout.write(f'{sec}')
stdout.flush()
prev_sec = sec
sleep(PAUSE)
print()
def get_cookies(d: WebDriver) -> WebDriver:
"""Сохранение или получение cookies.
"""
COOKIES_DIR.mkdir(exist_ok=True)
if path.exists(COOKIES_FILE):
d.get(URL)
with open(COOKIES_FILE, 'rb') as file:
for cookie in pickle.load(file):
d.add_cookie(cookie)
d.refresh()
logger.info('Cookies добавлены к драйверу.')
return d
d.get(URL + URL_LOGIN)
_wait(d, By.XPATH, login_by_password)
d.find_element(By.XPATH, login_by_password).click()
_wait(d, By.XPATH, login_input_username)
d.find_element(By.XPATH, login_input_username).send_keys(LOGIN)
d.find_element(By.XPATH, login_input_password).send_keys(PASSWORD)
d.find_element(By.XPATH, login_submit).click()
_wait(d, By.XPATH, mainmenu_my_resumes)
if _wait(d, By.XPATH, account_login_error):
raise LoginOrPasswordErrorException
with open(COOKIES_FILE, 'wb') as file:
pickle.dump(d.get_cookies(), file)
logger.info('Cookies записаны в файл.')
return d
txt = "CR2112-0718 192.168.1.1/24 192.168.1.2 192.168.1.3"
arr = txt.split()
for i in range(1, len(arr)):
if '/' in arr[i]:
print(f'subnet {arr[i]} 255.255.255.0')
else:
print(f'host {arr[i]}')
import re
txt = "CR2112-0718 192.168.1.1/24 192.168.1.2 192.168.1.3"
with_a_mask = re.findall(
r'([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}/[\d]{1,2})', txt
)
without_a_mask = re.findall(
r'([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})[^/]', txt
) # Не подхватывает последний ip
print(with_a_mask)
print(without_a_mask)
number = input()
result = 1
for index, value in enumerate(list(number), start=1):
result *= int(value) ** index
print(result)
word = 'python'
last_line = ''
with open('файл.log', encoding='utf-8') as file:
while True:
file_line = file.readline()
if not file_line:
break
if word in file_line:
last_line = file_line
print(last_line)
from file_read_backwards import FileReadBackwards
word = 'python'
with FileReadBackwards('log.log', encoding="utf-8") as frb:
while True:
line = frb.readline()
if not line:
break
if word in line:
print(line)
break
import re
test_list = [
'431234512 53 312451',
'431234512 53 3124512',
'431234512 53 31245133',
'431234512 53 312451324',
]
new_list = []
for line in test_list:
new_list.append(re.sub(r'(\d$)', r'0', line))
print(new_list)
[
'431234512 53 312450',
'431234512 53 3124510',
'431234512 53 31245130',
'431234512 53 312451320'
]
with open(COOKIES_FILE, 'wb') as file:
pickle.dump(driver.get_cookies(), file)
if path.exists(COOKIES_FILE):
driver.get(URL)
with open(COOKIES_FILE, 'rb') as file:
for cookie in pickle.load(file):
driver.add_cookie(cookie)
driver.refresh()
def get_source_html(url):
chrome_options = Options()
driver = Service(executable_path="C:\\webdrivers\\chromedriver.exe")
driver = webdriver.Chrome(options=chrome_options)
driver.maximize_window()
try:
driver.get(url=url)
time.sleep(3)
while True:
find_more_element = driver.find_element(
By.CLASS_NAME, "catalog-button-showMore")
if driver.find_elements(By.CLASS_NAME, "hasmore-text"):
with open("lesson6/source-page.html", "w") as file:
file.write(driver.page_source)
break
else:
actions = ActionChains(driver)
actions.move_to_element(find_more_element).perform()
time.sleep(3)
except Exception as ex:
print(ex)
finally:
driver.close()
driver.quit()
while True:
# Код / функция, которая будет всегда крутиться.
for /l %q in (0) do python my.py
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
URL = 'https://www.avito.ru/moskva/bytovaya_elektronika'
PAUSE_DURATION_SECONDS = 5
def main():
driver.get(URL)
sleep(PAUSE_DURATION_SECONDS)
if __name__ == '__main__':
try:
service = Service(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
main()
except Exception as e:
print(e)
finally:
driver.quit()