How to handle exit code in batch script? - python

I have a batch script which eventually runs two python file (one after another), but I am unable to handle the exit code from one workflow to another. Due to which my batch script is failing
batch file snippet:
#echo off
echo "Starting the automation Script"
cd "C:\Desktop\AutoImpement\"
echo "running the loging"
start python login.py
start python OrderTicket.py
pause
login script:
import time
from selenium import webdriver
browser = webdriver.Chrome(executable_path="C:\Desktop\AutoImpement\ChromeDriver")
browser.get('https://localhost:8080/login/#')
browser.find_element_by_id(“Login”).send_keys(“<userName>”)
browser.find_element_by_id (“Password”).send_keys(“password”)
browser.find_element_by_id(“submit”).click()
time.sleep(5)
browser.find_element_by_id(“ItemName”).send_keys(“test”)
browser.find_element_by_id (“Quantity”).send_keys(“5”)
browser.find_element_by_id(“Address”).send_keys(“Test”)
browser.find_element_by_id(“submitOrder”).click()
time.sleep(3)
browser.quit()
Verify the Order Script
import time
from selenium import webdriver
browser = webdriver.Chrome(executable_path="C:\Desktop\AutoImpement\ChromeDriver")
browser.get('https://localhost:8080/OrderDetails')
browser.find_element_by_id(“SreachOrder”).send_keys(“test”)
browser.find_element_by_id(“findOrder”).click()
time.sleep(3)
browser.quit()
When I run the batch file, only the login script is running successfully but the control is not shifting to the next script which verifies the order from the first file. I tried with sending the exit code from the python by changing the following but didn't work.
import time
from selenium import webdriver
try:
browser = webdriver.Chrome(executable_path="C:\Desktop\AutoImpement\ChromeDriver")
browser.get('https://localhost:8080/login/#')
browser.find_element_by_id(“Login”).send_keys(“<userName>”)
browser.find_element_by_id (“Password”).send_keys(“password”)
browser.find_element_by_id(“submit”).click()
time.sleep(5)
browser.find_element_by_id(“ItemName”).send_keys(“test”)
browser.find_element_by_id (“Quantity”).send_keys(“5”)
browser.find_element_by_id(“Address”).send_keys(“Test”)
browser.find_element_by_id(“submitOrder”).click()
time.sleep(3)
exit(0)
except:
print("Error Occured")
exit(1)
finally:
browser.quit()

In the above case in your batch file. Both the Scripts will run simultaneously.
Remove Start
python login.py
python OrderTicket.py
The Second will run only after first is complete.

Related

Python script runs fine from terminal but crashes when run from crontab

I have a simple python script that takes screenshots of a computer that is running Ubuntu. I want it to run automatically on startup, so I put #reboot python3 /bin/program.py in the non-sudo version of crontab.
The program works fine when run from terminal, but gives the error pyscreenshot.err.FailedBackendError. I put it in a try loop, and had it write all exceptions to a file, and that's how I found the error message, "All backends failed."
It has something to do with the program 'pyscreenshot' not working correctly.
import pyscreenshot as screen
import os
from numpy import random
from time import sleep
from os.path import expanduser
TMP_SCREEN_PATH = expanduser('~') + '/.UE/tmp.png'
LOG_FILE_PATH = expanduser('~') + '/.UE/log.txt'
GRAB_DELAY_RANGE = (1, 10)
def screenshot(save_path=TMP_SCREEN_PATH):
img = screen.grab()
img.save(save_path)
def delay(delay_range):
sleep_time = random.randint(delay_range[0], delay_range[1])
print(f"Sleeping for {sleep_time} seconds")
sleep(sleep_time)
def main():
try:
while True:
screenshot()
delay(GRAB_DELAY_RANGE)
except KeyboardInterrupt:
print("Nope")
main()
except Exception as e:
print(e)
with open(LOG_FILE_PATH, 'a') as f:
f.write(str(type(e))+str(e)+'\n')
sleep(5)
main()
f = open(LOG_FILE_PATH, 'w+')
f.write('Startup')
f.close()
main()
I need one of the following solutions:
Simply fix the problem
Another way to run a program at startup
A different module to take screenshots with
Any help is appreciated, thanks
If the user that the cron job runs as is also logged in on the console (you mention a reboot, so I'm guessing that you have enabled autologin), then your cron job might work if you also add:
os.environ["DISPLAY"] = ":0"
This worked for me on Ubuntu in a test using cron and a simplified version of your script:
import os
import pyscreenshot as screen
os.environ["DISPLAY"] = ":0"
img = screen.grab()
img.save("/tmp/test.png")
If it doesn't work for you, then you might also have to try setting the value of the XAUTHORITY environment variable to the value found in the environment of the user's interactive processes, which could be extracted using the psutil package, but let's hope this isn't needed.

How to initialize a Firefox profile programmatically

I want to programmatically initialize a Firefox profile so that all files that are normally created on first run of Firefox are created.
I have tried using firefox -CreateProfile but it only creates the folder and a times.json file. I need the full profile. What I probably need to do is start and close Firefox using Python, but I cannot get Firefox to close.
I am using subprocess.Popen so I can retrieve the pid to later close Firefox with proc.terminate(), but it is not working. The pid's process is no longer found. Perhaps it has something to do with Firefox multiprocess?
import os
import subprocess
import time
profile_name = 'new_profile'
profile_path = f"C:\\Users\\user\\profiles\\{profile_name}"
os.system(f'firefox -CreateProfile "{profile_name} {profile_path}" -no-remote')
proc = subprocess.Popen(['firefox', '-profile', profile_path, '-no-remote'])
print(f"Pid: proc.pid")
time.sleep(3)
proc.terminate() # Not working
time.sleep(1)
os.system(f"taskkill /F /pid {proc.pid}") # Process not found
Running the script and confirming with taskkill the process on the original pid is no longer found:
Pid: 16472
ERROR: The process "16472" not found.
How can I close Firefox using this approach?

How to make python loop interruptible by ^C on unix?

I've written a python script that looks up the recommended server at nordvpn.com and starts the according vpn. There is a part in this script where I assure there is internet access. When I run the script from a terminal, I cannot interrupt this loop by pressing ^C if there is no connection. How can I adapt the code so that the loop is interruptible?
Here is relevant part of the code:
#!/usr/bin/env python3
import re
import os
from selenium import webdriver
if __name__ == '__main__':
# ...
# wait for internet connection and load geckodriver
while True:
try:
browser = webdriver.Firefox(
executable_path=r'/home/maddin/bin/.vpn/geckodriver',
log_path='/dev/null')
break
except:
print("not connected yet, trying again....")
# ...
Using except: will catch all errors, including KeyboardInterrupt. You can instead use except Exception: which will not catch SystemExit, KeyboardInterrupt and GeneratorExit. This will allow you to break a loop with Ctrl + C. You can find more information here and here.
this is because of your default except block which takes all Interrupts including KeyboardInterrupt which is your ^C
while True:
try:
browser = webdriver.Firefox(
executable_path=r'/home/maddin/bin/.vpn/geckodriver',
log_path='/dev/null')
break
except KeyboardInterrupt:
# do whatever you want to do on ^C
except:
print("not connected yet, trying again...."

How to open and close Tor browser automatically with Python

I am playing around with web scraping and Tor.
I managed to make it work with both requests and Selenium + PhantomJS. However, I need that the Tor browser is opened for the script to work.
This is why I am trying now to automatise the complete process; that is: open Tor browser automatically, run some script and at the end close the browser automatically. But I am struggling with it.
#open Tor browser
os.system('open /Applications/TorBrowser.app')
#code to scrape
#close Tor browser
???
Open
To open the browser, some other options I found out there are not working.
import subprocess
subprocess.Popen('/Applications/TorBrowser.app') #permission denied
or
os.system('start /Applications/TorBrowser.app') #sh: start: command not found
However, the following line worked:
os.system('open /Applications/TorBrowser.app')
Close
The main problem is to close the browser afterwards, as none of the commands found in other posts worked.
Those include:
os.system("taskkill /im /Applications/TorBrowser.app /f") #sh: taskkill: command not found
or
os.system("kill /Applications/TorBrowser.app") #sh: line 0: kill: /Applications/TorBrowser.app: arguments must be process or job IDs
or
os.close('/Applications/TorBrowser.app') #TypeError: an integer is required (got type str)
Any suggestions of how to close it?
And is there a better way to open it?
Edit: I'm on Mac with Python 3.
This worked for me:
from selenium import webdriver
import os
import subprocess
#start Tor
sproc=subprocess.Popen('"C:\\Users\\My name\\Desktop\\Tor Browser\\Browser\\firefox.exe"' )
#start PhantomJS
service_args = [ '--proxy=localhost:9150', '--proxy-type=socks5', ]
driver = webdriver.PhantomJS(service_args=service_args)
#get page
driver.get("https://stackoverflow.com/questions/40161921/how-to-open-and-close-tor-browser-automatically-with-python")
print(driver.page_source)
driver.close()
#kill process
sproc.kill()
I think you should add some time pauses between commands:
import time
time.sleep(20)# wait 20 seconds
Another way to open Tor:
os.system('"C:\\Users\\My Name\\Desktop\\Tor Browser\\Browser\\firefox.exe"' )
But this time your command will wait until the called process stops himself (may be user will close it). According to your question it is not what you want. To control executing process let it runs and use special variable to kill it whenever you want.
Also pay attention to string path: double quotes inside single quotes. There are other ways to pass strings with spaces to system commands, for example: running an outside program (executable) in python?.
Try this in jupyter:
import webbrowser
urL='https://YOUR WEBSITE ADDRESS HERE'
mozilla_path="C:\\Users\\T14s\\Desktop\\Tor Browser\\Browser\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path))
webbrowser.get('firefox').open_new_tab(urL)
import os
import time
time.sleep(10)
os.system("taskkill /im firefox.exe /f")
TOR is based on firefox - hence firefox comes up a lot.

Python - how to run the application and leave until it end?

How can i run the application and leave instead of waiting when it will be ended? for example : /var/tmp/runme.sh &
Following code is working but it waits forever when Google Chrome will exit. how can i run Google Chrome but let my script exit?
import subprocess
import sys
import time
line = sys.argv[1]
print line
def kill_chrome():
subprocess.call(['Taskkill', '/IM', 'chrome.exe', '/F'])
def run_chrome():
subprocess.call(['C:/Program Files (x86)/Google/Chrome/Application/chrome.exe', '--kiosk'])
def run_java():
subprocess.call(['java', '-cp', 'C:/Python27/pdfbox-app-2.0.0-RC3.jar;C:/Python27/jprint.jar', 'JPrint'])
try:
if line.startswith("myjava:website"):
print "Google Chrome - IDLE"
run_chrome()
elif line.startswith("myjava:a4"):
print "Printing - JAVA"
run_java()
elif line.startswith("myjava:kill"):
print "Killer"
kill_chrome()
except Exception, err:
print (err)
pass
#time.sleep(2)
What about subprocess.Popen? Looks like it does exactly what you want - runs app end does not waiting. You also pass arguments to the runned application.
from subprocess import Popen
Popen( [ "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", "myarg"])
Without "myarg" it works too.

Categories

Resources