I use Application from pywinauto.application
After logging in i want it to execute commads like :
putty.type_keys("ls")
putty.type_keys("{ENTER}")
To execute next command i need to wait for this one to end. Instead of typing something like :
time.sleep(5)
I need the program to know when the command is done and ready for next command, not to wait X seconds and hope the running task will be over untill that(for example downloadign a file). I looked up into "wait()", but didn't find anything useful. Any help?
You don’t need pywinauto for executing console commands by ssh! Just do something like this:
import subprocess
output = subprocess.check_output(“ssh user:password#hostname ls -l /home”)
for line in output.split(“\n”):
subpath = “ “.join(line.split(“ “)[1:])
print(subpath)
Related
How to use subprocess to terminate a program which is started at boot?
I ran across this question and found wordsforthewise's answer and tried it but nothing happens.
Wordsforthewise' Answer:
import subprocess as sp
extProc = sp.Popen(['python','myPyScript.py']) # runs myPyScript.py
status = sp.Popen.poll(extProc) # status should be 'None'
sp.Popen.terminate(extProc) # closes the process
status = sp.Popen.poll(extProc) # status should now be something other than 'None' ('1' in my testing)
I have a program /home/pi/Desktop/startUpPrograms/facedetection.py running at boot by a Cronjob and I want to kill it from a flask app route like this.
Assigning program name to extProc = program_name would work? If yes how to assign it?
#app.route("/killFD", methods=['GET', 'POST'])
def killFaceDetector():
#kill code goes here.
Since you say the program is run by cronjob, you will have no handle to the program's PID in Python.
You'll have to iterate over all processes to find the one(s) to kill... or more succinctly, just use the pkill utility, with the -f flag to have it look at the full command line. The following will kill all processes (if your user has the permission to do so) that have facedetection.py in the command line.
import os
os.system('pkill -f facedetection.py')
Actually, I have written a code where I've to lunch the application such that I've to click the on-screen keyboard using this pyautogui.click(). But it is not working on on-screen keyboard. I'll be pleased to have your precious opinion. Thanks in advance.
import os
import pyautogui as pg
import time
x= 195
y=505
secret="secretpassword"
command = "application"
os.system(command)
pg.click(x, y)
pg.typewrite(secret)
pg.typewrite(["enter"])
If the application is already lunched this is working but i want to lunch it with os.system(command)
and after that enter my password and access to the application.
Am I doing something wrong ?
I changed
os.system(command)
with
subprocess.Popen(command)
Now it's working
subprocess.Popen() is strict super-set of os.system().
os.system() will block and wait for the application to exit.
This means that your click, in fact, will not execute until the opened appication closes.
To verify this, you can open a (python) shell and run following code:
import os
import pyautogui
def test():
os.system('<something simple opening a window>')
pyautogui.typewrite("I'm in the shell again!")
test()
To run your script as you want, use os.popen, or, even better, subprocess.Popen. These will run the command without blocking.
If you do this, keep in mind your application will have startup time, so you will want to wait some time after the call as noted in the comments under your question.
I have some script in Python, which does some work. I want to re-run this script automatically. Also, I want to relaunch it on any crashes/freezes.
I can do something like this:
while True:
try:
main()
except Exception:
os.execv(sys.executable, ['python'] + sys.argv)
But, for unknown reason, this still crashes or freezes one time in few days. So I see crash, write "Python main.py" in cmd and it started, so I don't know why os.execv don't do this work by self. I guess it's because this code is part of this app. So, I prefer some script/app, which will control relaunch in external way. I hope it will be more stable.
So this script should work in this way:
Start any script
Check that process of this script is working, for example check some file time change and control it by process name|ID|etc.
When it dissapears from process list, launch it again
When file changed more than 5 minutes ago, stop process, wait few sec, launch it again.
In general: be cross-platform (Linux/Windows)
not important log all crashes.
I can do this by self (right now working on it), but I'm pretty sure something like this must already be done by somebody, I just can't find it in Google\Github.
UPDATE: added code from the #hansaplast answer to GitHub. Also added some changes to it: relauncher. Feel free to copy/use it.
As it needs to work both in windows and on linux I don't know a way to do that with standard tools, so here's a DIY solution:
from subprocess import Popen
import os
import time
# change into scripts directory
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
while True:
p = Popen(['python', 'my_script.py', 'arg1', 'arg2'])
time.sleep(20) # give the program some time to write into logfile
while True:
if p.poll() != None:
print('crashed or regularly terminated')
break
file_age_in_s = time.time() - os.path.getmtime('output.log')
if file_age_in_s > 60:
print('frozen, killing process')
p.kill()
break
time.sleep(1)
print('restarting..')
Explanation:
time.sleep(20): give script 20 seconds to write into the log file
poll(): regularly check if script died (either crashed or regularly terminated, you can check the return value of poll() to differentiate that)
getmtime(): regularly check output.log and check if that was changed the past 60 seconds
time.sleep(1): between every check wait for 1s as otherwise it would eat up too many system resources
The script assumes that the check-script and the run-script are in the same directory. If that is not the case, change the lines beneath "change into scripts directory"
I personally like supervisor daemon, but it has two issues here:
It is only for unix systems
It restarts app only on crashes, not freezes.
But it has simple XML-RPC API, so It makes your job to write an freeze-watchdog app simplier. You could just start your process under supervisor and restart it via supervisor API when you see it freezes.
You could install it via apt install supervisor on ubuntu and write config like this:
[program:main]
user=vladimir
command=python3 /var/local/main/main.py
process_name=%(program_name)s
directory=/var/local/main
autostart=true
autorestart=true
I have a batch program that simply pings in loop with 'ping adress -t'. Adress being whatever I'm trying to ping at the time.
I'd like to do something similiar with python, but without the popup of a command prompt window and thus I'd like to avoid anything that would do this. I want a way to print it ONLY to the python window, so I can use it in my Tkinter program.
This is what I would originially thought would work, and it does, but I want the output to be in the python window, not in the command prompt.
import subprocess
subprocess.call(["ping", "google.com", "-t"])
What about:
import subprocess
subprocess.call(["ping", "-t"])
I am running several processes over a cluster.
I start every process separately using screen command.
It allows me to disconnect from the cluster and when connected view my processes.
Starting all the screens one by one is a painful job.
I am wondering if we could do it with a python script.
The scrip opens the new shell creates the screen runs the process and disconnects.
Writes info about all the started processes in a text file like process id starting commands etc.
Secondly, I would like to stop the processes, I would like to put the pid to file and just run a command which will kill all the mentioned processes.
for example
the smaple inut file looks like
process_name command
123 python batch_training.py
I would like to start the screen with the name given in process_name and the commend will be executed in the corresponding frame.
Thanks
Can you give the screen object a command in python?
Like:
from os import system
command = 'screen ' + '/dev/ttyUSB0 38400'
result = system(command)
result('ATZ')???
If you want to run your command without opening screen session, you should also use -dmS options with screen. So if you want to do that with python, Your code could look like this:
import subprocess
subprocess.call(["screen", "-dmS", "screen_name_1", "top"])
subprocess.call(["screen", "-dmS", "screen_name_2", "top"])
subprocess.call(["screen", "-r"])
Try to use "os.system()" with standart Linux commands.
e.g.:
os.system("screen nano")
In general, in python, you can run system commands by running
from os import system
and then
system('whatever_shell_command')
So in your case you would type:
from os import system
system('screen')
Unfortunately (this is only sort of related) you can't run more then one command together, so
system('shell_command ', argument)
will not work.
so if you want to do that, you will need to concatenate the two strings:
full_command = 'shell_command ' + argument
system(full_command)`