Killing a Windows 7 program using Python 2.7x - python-2.7

I currently have the below code:
processlist = []
for p in psutil.process_iter():
try:
process = psutil.Process(p.pid)
pname = process.name()
processlist.append(pname)
except:
pass
if "tor.exe" in processlist:
os.system("Taskkill /im tor.exe")
process = subprocess.Popen(r"C:\Program Files (x86)\Tor Browser\Browser\firefox.exe", stdout=subprocess.PIPE)
In essence,I want the Python code to kill the Tor Browser if it is open and to then reopen it. Nonetheless, when I run this code, the Tor browser displays a message stating that there is an error with the Browser and would the user like to close and restart the browser? I don't really want this to happen and so I'm just wondering if there is another way of closing the browser avoiding this confirmation prompt message?

Type taskkill /?
All you are doing is asking Tor (whatever that is) to close, ie send a WM_Close message. /f terminates an application.

Related

How to force quit my python-made exe

I've got a little python app that I used pyInstaller on to create an exe file:
import subprocess
try:
taskCommand = 'tasklist /FI "ImageName eq pc-client.exe"'
reply = subprocess.Popen(taskCommand, stdout = subprocess.PIPE).communicate()[0]
for line in reply.split("\n"):
if line.startswith("pc-client.exe"):
PID = line.split()[1]
print PID
except:
pass
try:
killCommand = ("TASKKILL /f /t /PID " + PID)
subprocess.Popen(killCommand, stdout = subprocess.PIPE).communicate()[0]
except:
pass
try:
print "Restarting Papercut Client..."
subprocess.Popen(r"\\server\path\to\file\filename.exe", stdout = subprocess.PIPE).communicate()[0]
except:
pass
sys.exit()
When the exe is run, it opens up in the windows command window, will run its code (it's non-interactive) and then I want the window to dissappear when its finished!
What should I put at the end of my python code to make the window close when completed. I've tried os.quit(), os._exit(), sys.quit() & sys.exit() but none of them actually close the window!
As I'm creating an exe from my code, should I use something else? I can't compile with the noconsole flag, as it needs it to actually run the commands...
Thanks.
You can block the windows command prompt from coming up at all by putting
console=False
in your spec file. For example:
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='YourApp',
console=False,
icon='IMGFolder\game_icon_cs6_icon.ico')
If you are running from the command line without a spec file, use the noconsole flag:
pyinstaller.py --noconsole yourscript.py
for more info on the PyInstaller options: https://pyinstaller.readthedocs.io/en/stable/usage.html#options
If you want the prompt to come up then close, sys.exit() works for me, but without seeing more code it will be hard to tell.
UPDATE
Since subprocesses are involved, keep in mind that the command prompt will remain open until all processes are resolved (parent and child).
It looks like you are killing the first task with its PID (I would print out the PID before you kill it to confirm you have the right one). Then you run the second task (the main file you want run?) but never kill it.
Are you trying to close the command prompt but keep the .exe running?
There is some good information about killing processes here:
How to kill a python child process created with subprocess.check_output() when the parent dies?

Python selenium CTRL+C closes chromedriver

How can I catch CTRL+C (a KeyboardInterrupt) without causing the chromedriver to close.
It closes the chromedriver when I run my script.py through cmd.
driver = webdriver.Chrome()
try:
while True:
#do stuff with chromedriver
except KeyboardInterrupt:
print "User pressed CTRL + C"
#do other stuff with chromedriver
It does catch the KeyboardInterrupt in my script, thus my script continues but the chromedriver also gets it and close itself.
EDIT 1:
The solution here doesn't work when you run the script through CMD or when you freeze the script with Pyinstaller and run it (IOError: [Errno 4] Interrupted function call)
EDIT 2:
I also tried by making the script ignore the Errno 4 (using try and except Exception) but still has the same result (chromedriver closes) so in short, this solution does not help at all.
Consider using the webdriver.Remote flavor. This option does not spawn a local version of the webdriver inside the interpreter, which should free you from the SIGINT hassle.
Initiate the webdriver in another shell - (chromedriver for Chrome, geckodriver for Firefox, etc.)
Take note of the listening port. I will use the defaults here: 9515 for chromedriver and 4444 for geckodriver.
In your python script:
Chrome:
driver=webdriver.Remote("http://127.0.0.1:9515",desired_capabilities=webdriver.DesiredCapabilities.CHROME)
Firerox:
driver=webdriver.Remote("http://127.0.0.1:4444",desired_capabilities=webdriver.DesiredCapabilities.FIREFOX)
I just tried #Krmit 's answer, with Selenium 4.8.2, python 3.11, and Geckodriver and it worked fine for what I wanted (to be able to cancel a sleep).
options=Options()
# options.profile = FirefoxProfile()
ps = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, signal.SIG_IGN)
driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), options=options)
signal.signal(signal.SIGINT, ps)
You can also just disable SIGINT handling while starting the driver. Like so:
import signal
...
ps = signal.getsignal(signal.SIGINT) # backup signal handler
signal.signal(signal.SIGINT, signal.SIG_IGN) # ignore signal temporarily
... = webdriver.Chrome(...)
signal.signal(signal.SIGINT, ps) # restore original handler

subprocess.popen stream handling

Is it possible to prevent subprocess.popen from showing prompts in the terminal?
Attempting to map a drive but would like to read the prompt for credentials in the script rather than display them to the terminal. The idea being I can carry out actions based on the response.
I am aware the use of shell is frowned upon when using string based commands (for obvious reasons), however I'm controlling the input so am happy with the risk for testing purposes.
I was under the impression that all stdout (interaction) would be parsed into the output_null variable. Instead I am still getting the prompt in the terminal (as illustrated below). I'm either miss understanding how the streams work or I'm missing something. Can anyone enlighten me please
command = "mount -t smbfs //{s}/SYSVOL {m}".format(s=server, m=temp_dir)
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output_null = p.communicate()[0]
if "Password for" in output_null:
print 'awdaa'
Terminal Shows
Password for 192.168.1.111:

How to read text from an application window using pywinauto

I have a python code which opens a SSH session using Putty and passes a command to reboot a remote machine using pywinauto.
I want to read the text from the putty terminal after typing the password and compare it
Is there a way I can do it?
Below is the piece of code for the same
app_Putty = application.Application()
app_Putty.start_("C:\Users\debajyoti.bose\Downloads\putty.exe")
app_Putty.top_window_().TypeKeys(IP)
app_Putty.top_window_().TypeKeys("{TAB}"+"22")
app_Putty.top_window_().RadioButton4.Click()
app_Putty.top_window_().OpenButton.Click()
time.sleep(10)
app_Putty.top_window_().NoButton.Click()
time.sleep(2)
app_Putty.top_window_().TypeKeys(user+"{ENTER}")
time.sleep(3)
app_Putty.top_window_().TypeKeys(password+"{ENTER}")
time.sleep(3)
app_Putty.top_window_().TypeKeys("/bin/reboot"+"{ENTER}")
time.sleep(5)
app_Putty.kill_()
time.sleep(120)
I am using pywinauto v0.4.0
Thanks in advance.
OK, let's try app_Putty.top_window_().WindowText(). If it fails your mission looks impossible.
You can't capture directly like this from what I can tell, but I had to find a workaround, and the one I found was this
#clear the buffer with alt space menu
app.window(title='PuTTY - Title').type_keys('% l',with_spaces=True)
#copy the buffer to clipboard
app.window(title='PuTTY - Title').type_keys('% o',with_spaces=True)
I was having to do this because the putty.log file was missing the selection indicator icon (asterisk) on the screen when it was logging output and I needed a way to know which item was selected to move up or down.

Condor output file updating

I'm running several simulations using Condor and have coded the program so that it outputs a progress status in the console. This is done at the end of a loop where it simply prints the current time (this can also be percentage or elapsed time). The code looks something like this:
printf("START");
while (programNeedsToRum) {
// Run code repetitive code...
// Print program status update
printf("[%i:%i:%i]\r\n", hours, minutes, seconds);
}
printf("FINISH");
When executing normally (i.e. in the terminal/cmd/bash) this works fine, but the condor nodes don't seem to printf() the status. Only once the simulation has finished, all the status updates have been outputted to the file but then it's no longer of use. My *.sub file that I submit to condor looks like this:
universe = vanilla
executable = program
output = out/out-$(Process)
error = out/err-$(Process)
queue 100
When submitted the program executes (this is confirmed in condor_q) and the output files contain this:
START
Only once the program has finished running its corresponding output file shows (example):
START
[0:3:4]
[0:8:13]
[0:12:57]
[0:18:44]
FINISH
Whilst the program executes, the output file only contains the START text. So I came to the conclusion that the file is not updated if the node executing program is busy. So my question is, is there a way of updating the output files manually or gather any information on the program's progress in a better way?
Thanks already
Max
What you want to do is use the streaming output options. See the stream_error and stream_output options you can pass to condor_submit as outlined here: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html
By default, HTCondor stores stdout and stderr locally on the execute node and transfers them back to the submit node on job completion. Setting stream_output to TRUE will ask HTCondor to instead stream the output as it occurs back to the submit node. You can then inspect it as it happens.
Here's something I used a few years ago to solve this problem. It uses condor_chirp which is used to transfer files from the execute host to the submitter. I have a python script that executes the program I really want to run, and redirects its output to a file. Then, periodically, I send the output file back to the submit host.
Here's the Python wrapper, stream.py:
#!/usr/bin/python
import os,sys,time
os.environ['PATH'] += ':/bin:/usr/bin:/cygdrive/c/condor/bin'
# make sure the file exists
open(sys.argv[1], 'w').close()
pid = os.fork()
if pid == 0:
os.system('%s >%s' % (' '.join (sys.argv[2:]), sys.argv[1]))
else:
while True:
time.sleep(10)
os.system('condor_chirp put %s %s' % (sys.argv[1], sys.argv[1]))
try:
os.wait4(pid, os.WNOHANG)
except OSError:
break
And my submit script. The problem ran sh hello.sh, and redirected the output to myout.txt:
universe = vanilla
executable = C:\cygwin\bin\python.exe
requirements = Arch=="INTEL" && OpSys=="WINNT60" && HAS_CYGWIN==TRUE
should_transfer_files = YES
transfer_input_files = stream.py,hello.sh
arguments = stream.py myout.txt sh hello.sh
transfer_executable = false
It does send the output in its entirety, so take that in to account if you have a lot of jobs running at once. Currently, its sending the output every 10 seconds .. you may want to adjust that.
with condor_tail you can view the output of a running process.
to see stdout just add the job-ID (and -f if you want to follow the output and see the updates immediately. Example:
condor_tail 314.0 -f