I can't get this to run on start Up - python

I have this python code, which when I run it, it works and brings me to YouTube. I'm trying to get it so every time I boot up the raspberry pi it will run my python code and take me straight to YouTube. The rc.local file runs but it says
could not locate runnable browser
Here is my python program
import webbrowser, os, sys
url = "http://www.youtube.com"
chrome_path = '/usr/lib/chromium-browser/chromium-browser'
def main():
webbrowser.get(chrome_path).open(url)
main()
Here is my rc.local file
python /home/pi/browserOpen/OpenBrowser.py &
exit 0

Try to change your main() function like this:
def main():
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path), 1)
webbrowser.get('chrome')
webbrowser.open(url, new=2)
and set chrome_path to "/usr/bin/chromium-browser/chromium-browser"
UPDATE:
Try creating .sh file in the same directory as your .py file, put /yourpath/bin/yourscript.sh & in rc.local and this code:
#!/bin/sh
sleep 10
python scriptname.py
in yourscript.sh file.
Original answer from here

Related

Why does Win 7 make a beep when I run a Python script?

I have seen a few question asking how to make a Python script that makes a beep sound.
This question is not about that.
When I run certain Python scripts Windows 7 makes a beep sound but I want to stop the beep.. or at least understand why it's happening.
Here is a test script - test.py:
#!/usr/bin/python
# importing modules
import os
import time
import datetime
from datetime import datetime
def f_log(strtext):
# In this method try and write to the log file
logFilePath = '/home/osmc/python/pyscripter_file.txt'
ts_local = datetime.now()
ts = ts_local.strftime("%d/%b/%Y %H:%M:%S")
try:
# Check if the logfile exists
if(os.path.isfile(logFilePath)):
# Append the error message to the log file. 'a+' creates the file if it does not exist.
with open(logFilePath, 'a+') as f:
f.write(ts + '\t' + strtext + '\n')
else:
print("Log File does not exist - Creating File now")
with open(logFilePath, 'a+') as f:
f.write(ts + '\t' + 'Log File does not exist - Creating File now' + '\n')
f.write(ts + '\t' + strtext + '\n')
except IOError as e:
# Handle the exception
print("Error Msg")
f_log("Test Script")
print("Hello World")
This script is in a directory on a Raspberry Pi running OSMC... in a folder called /home/osmc/python
I have opened it as a remote file in the Pyscripter IDE and can see ssh://osmc//home/osmc/python/test.py
So this means, the Pyscripter IDE, running on Windows 7, is running the Python script on the remote machine. When I run the script this way I get a beep when it finishes executing.
If I create a crontab to run it in osmc...
PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/bin/python
53 22 * * * /usr/bin/python /home/osmc/python/test.py >> out.txt 2>&1
Then the script also gives a beep at the end of execution.
If I run the script from a command line to osmc (from an ssh connection in Putty)
# cd /home/osmc/python
# python test.py
I DO NOT get a beep when it completes.
If I run this next script in Pyscripter (or any other way) it does NOT make a beep.
import sys
print('Python '+sys.version.replace('\n','')+' at '+sys.executable+' on '+sys.platform)
Why do I sometimes get the beep? Something in the Python code in the first script I guess?
Flex
My test Python script writes to a log file. I had that log file open in PyScripter IDE.
PyScripter IDE by design makes a beep to signal a File Change Notification affecting any files open in the IDE. This is what was causing the beep whether I was running the script from within PyScripter or not I was still getting the beep because the script was writing to the file open in PyScripter IDE.
I asked the developer and it is currently not possible to turn off this beep.
Flex

Python Script doesn´t work when started via other script

I´m currently working on a raspberry pi 4 and wrote a script in python that send a mail with a picture and then rename the file and puts it in another folder.
The script works fine when I start with command
sudo python script.py
but when start it with another script it won´t execute the part with the renaming
Now the question what is my mistake ?
import os
import time
from sendmail import mail
from sendmail import file_rename
from time import sleep
pic = '/home/pi/Monitor/Bewegung.jpg'
movie= '/home/pi/Monitor/Aufnahme.avi'
archiv = '/home/pi/Archiv/'
time = time.strftime('%d.%m.%Y %H:%M')
mail(filename = pic )
file_rename(oldname = pic ,name = 'Serverraum Bild' + time ,format = '.jpg' ,place = archiv )
file_rename(oldname = movie ,name = 'Serverraum Video' + time ,format = '.avi' ,place = archiv )
I see that you are starting the script as a user with sudo privileges.
but when start it with another script it won´t execute the part with the renaming
This makes me suspicious that the caller script does not have the correct permissions to rename/move a file. You can view the permissions of the script with the following command
ls -la callerscript.py

How to run python program automatically even if system restarted

I want to run my python API continuously (means program API will all-time active if call then it work) even if a system restarts my python API automatically restart.
I have API URL: http://localhost:8002/city_id_pred?id=1,2 through this URL calling python API.
Program:
import web
import pyodbc
import re
import numpy as np
#from wordcloud import WordCloud, STOPWORDS
from collections import Counter
from sklearn.externals import joblib
import pandas as pd
cnxn = pyodbc.connect('')
cursor = cnxn.cursor()
urls = (
'/city_id_pred?', 'Predict'
#'/', 'MyApplication'
)
class Predict(web.application):
def run(self, port=8080, *middleware):
func = self.wsgifunc(*middleware)
return web.httpserver.runsimple(func, ('0.0.0.0', port))
print("Start class...")
def GET(self):
#here prediction model
if __name__ == "__main__":
app = Predict(urls, globals())
app.run(port=8002)
Please suggest
Actually, I want to run on window server but currently using in windows OS.
As #Mubarak said, you basically want to convert it to a .exe and then add that .exe to startup.
I would recommend that you do this by using PyInstaller and then following this tutorial on how to add that .exe to your startup.
Following step will help you:
Make your python code like example.py
Convert example.py to example.exe file by using auto-py-to-exe https://pypi.org/project/auto-py-to-exe/
Open Task Schedular in your window system
Create Task->Gentral Tab ->Give Name,Location
Trigger Tab->Bigin the Task->On Startup
Hope this helps
Following given steps,.
1.Convert your python file to .exe format(https://pypi.org/project/auto-py-to-exe/)
Make simple batch file to run the .exe file which your python file.
#echo off
cd "C:\Program Files\Google\Chrome\Application\"
Start chrome.exe
start – "C:\Program Files\Microsoft Office\Office15\WINWORD.EXE"
"C:\Work\MUO\How to Batch Rename.docx"
cd "C:\Program Files (x86)\VMware\VMware Player"
start vmplayer.exe
exit
Hope your understood,....

Cannot get #reboot Cron job to run Python script

I have a cron job that loads a Python script on reboot but it will just not work.
I have checked the Python script and that works fine from CLi.
The .py basically loads a browser to Google and then sends it to full screen.
(It actually loads another website and enters login details also, but removed for obvious reasons)
Been at this for weeks now and driving me crazy, any ideas?
Raspberry Pi running Raspbian.
$crontab -e
#reboot DISPLAY=:0 python /prtgboot.py
prtgboot.py
'#'!/usr/bin/env python
import commands
import time
webbrowser = "iceweasel"
pgrepcmd = "pgrep %s " % (webbrowser)
process = commands.getoutput(pgrepcmd)
if process == "":
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
browser = webdriver.Firefox()
actions = ActionChains(browser)
browser.get('http://google.co.uk')
elemFullscreen = browser.find_element_by_tag_name('html')
time.sleep(30)
elemFullscreen.send_keys (Keys.F11)
exit()
else:
exit()
Ok, so Petesh was correct. It was #reboot not working correctly.
Changed the cron to * * * * * so my script runs every minute. Normally bad practice, but already setup script to end if browser already running. Working a treat now.
On a positive note, if the browser crashes it will start again for me :)

Python - How do you run a .py file?

I've looked all around Google and its archives. There are several good articles, but none seem to help me out. So I thought I'd come here for a more specific answer.
The Objective: I want to run this code on a website to get all the picture files at once. It'll save a lot of pointing and clicking.
I've got Python 2.3.5 on a Windows 7 x64 machine. It's installed in C:\Python23.
How do I get this script to "go", so to speak?
=====================================
WOW. 35k views. Seeing as how this is top result on Google, here's a useful link I found over the years:
http://learnpythonthehardway.org/book/ex1.html
For setup, see exercise 0.
=====================================
FYI: I've got zero experience with Python. Any advice would be appreciated.
As requested, here's the code I'm using:
"""
dumpimages.py
Downloads all the images on the supplied URL, and saves them to the
specified output file ("/test/" by default)
Usage:
python dumpimages.py http://example.com/ [output]
"""
from BeautifulSoup import BeautifulSoup as bs
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
import os
import sys
def main(url, out_folder="C:\asdf\"):
"""Downloads all the images at 'url' to /test/"""
soup = bs(urlopen(url))
parsed = list(urlparse.urlparse(url))
for image in soup.findAll("img"):
print "Image: %(src)s" % image
filename = image["src"].split("/")[-1]
parsed[2] = image["src"]
outpath = os.path.join(out_folder, filename)
if image["src"].lower().startswith("http"):
urlretrieve(image["src"], outpath)
else:
urlretrieve(urlparse.urlunparse(parsed), outpath)
def _usage():
print "usage: python dumpimages.py http://example.com [outpath]"
if __name__ == "__main__":
url = sys.argv[-1]
out_folder = "/test/"
if not url.lower().startswith("http"):
out_folder = sys.argv[-1]
url = sys.argv[-2]
if not url.lower().startswith("http"):
_usage()
sys.exit(-1)
main(url, out_folder)
On windows platform, you have 2 choices:
In a command line terminal, type
c:\python23\python xxxx.py
Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.
For your posted code, the error is at this line:
def main(url, out_folder="C:\asdf\"):
It should be:
def main(url, out_folder="C:\\asdf\\"):
Usually you can double click the .py file in Windows explorer to run it. If this doesn't work, you can create a batch file in the same directory with the following contents:
C:\python23\python YOURSCRIPTNAME.py
Then double click that batch file. Or, you can simply run that line in the command prompt while your working directory is the location of your script.
Since you seem to be on windows you can do this so python <filename.py>. Check that python's bin folder is in your PATH, or you can do c:\python23\bin\python <filename.py>. Python is an interpretive language and so you need the interpretor to run your file, much like you need java runtime to run a jar file.
use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.
Your command should include the url parameter as stated in the script usage comments.
The main function has 2 parameters, url and out (which is set to a default value)
C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"
If you want to run .py files in Windows, Try installing Git bash
Then download python(Required Version) from python.org and install in the main c drive folder
For me, its :
"C:\Python38"
then open Git Bash and go to the respective folder where your .py file is stored :
For me, its :
File Location : "Downloads"
File Name : Train.py
So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"
then i will run the below command
" /c/Python38/python Train.py "
and it will run successfully.
But if it give the below error :
from sklearn.model_selection import train_test_split
ModuleNotFoundError: No module named 'sklearn'
Then Do not panic :
and use this command :
" /c/Python38/Scripts/pip install sklearn "
and after it has installed sklearn go back and run the previous command :
" /c/Python38/python Train.py "
and it will run successfully.
!!!!HAPPY LEARNING !!!!

Categories