I am trying to run a python script at ubuntu startup.
The script(play.py) plays a youtube video in chrome browser.
import webbrowser
import time
import subprocess as sp
val = 0;
while(val <1):
time.sleep(1)
#webbrowser.open("https://www.youtube.com/watch?v=dO1rMeYnOmM")
child = sp.Popen("google-chrome %s" % "https://www.youtube.com/watch?v=dO1rMeYnOmM", shell=True)
val = val +1
To run this script at ubuntu startup I added the following entry in rc.local:
python /home/user_name/Desktop/python/play.py &
And changes the mode of play.py to 777.
I also tried copying this script file to /etc/init.d.
But still the script does not execute at system startup.
Try sudo /usr/bin/python /home/user_name/Desktop/python/play.py & instead.
Related
Running RPi4s with Ubuntu Server 19.10, Python 3.7.5, python3-xlib==0.15 and pyautogui==0.9.50. Everything is run as the default ubuntu user.
I'm trying to have Machine A send an ssh command to Machine B to run a GUI program and do some processing. I'm getting some XAUTHORITY errors.
Note: I don't want to see the GUI on Machine As monitor - but the app running on Machine B needs a GUI.
So on Machine A I run:
subprocess.Popen(['ssh', 'ubuntu#ip_of_machine_B', 'python3', '/path/to/my_script.py'])
On Machine B, my_script.py executes
subprocess.call(['python3', '/path/to/gui_script.py'])
Finally, gui_script.py attempts to
import os
os.environ['DISPLAY'] = ':0'
os.environ['XAUTHORITY'] = '/run/user/1000/gdm/Xauthority'
import subprocess
import pyautogui
subprocess.Popen(['the_gui_app'])
# Do stuff with pyautogui and the app.
Unfortunately, gui_script.py is throwing the following
Xlib.error.DisplayConnectionError: Can't connect to display ":0": No protocol specified.
I also tried setting the environment in the subprocess call in my_script.py via
my_env = os.environ.copy()
my_env['DISPLAY'] = ':0'
my_env['XAUTHORITY'] = '/run/user/1000/gdm/Xauthority'
subprocess.call(['python3', '/path/to/gui_script.py'], env=my_env)
But that also failed.
My best guess is I need to change some setting somewhere on Machine B prior to running the workflow (ie, a one-time edit to xauth)? This is a closed system so security isn't an issue!
I'm on Ubuntu 16.04.1, and I have a python script to download image files from websites, the codes are as follows:
import sys
import os
import time
import json
import shlex, subprocess
import signal
import random
R = 0
r = 0
targets = ['192.0.78.13', '134.109.133.7', '216.58.212.227', '54.246.159.107', '185.60.216.35', '98.136.103.24']
if __name__ == "__main__":
while True:
cmd = 'wget -A pdf,jpg,png -m -p -E -k -K -np --delete-after '
R = random.randint(0,5)
cmd += targets[R]
args = shlex.split(cmd)
p = subprocess.Popen(args, shell=False)
time.sleep(2.0)
# killing all processes in the group
os.kill(p.pid, signal.SIGTERM)
if p.poll() is None: # Force kill if process
os.kill(p.pid, signal.SIGKILL)
r = random.randint(3,20)
time.sleep(r-1)
it run perfectly with command "python webaccess.py", now I want to run it automatically on startup in the background.
I've tried two methods but all of them are fail (the scripty does not run):
Use crontab using the guide here: Run Python script at startup in Ubuntu
#reboot python /bin/web1.py &
Edit the rc.local using the guide here: https://askubuntu.com/questions/817011/run-python-script-on-os-boot
python /bin/web1.py &
Is there any way to solve this?
Thank you in advance.
your rc.local method should work, check using your full python path. if that is default /usr/bin/python
/use/bin/python your_file_py
also you said you verified python webaccess.py do verify it from outside the folder of script.
also note that scrips in rc.local are executed by root
so check path_to_python python_file from root #
I am new to Kafka but have seen a few tutorials so I know how Kafka works. I am trying to run a producer that I have written in Python but I don't know how to run this file after I have started my zookeeper server and kafka server. If anyone can tell me the structure of the command that is to be written in command prompt, I would really appreciate it.
Thanks!
Kafka Producer:
import json
import time
from kafka import KafkaProducer
from kafka.errors import KafkaError
from kafka.future import log
if __name__ == "__main__":
producer = KafkaProducer(bootstrap_servers= 'localhost: 9092')
future = producer.send('my-topic', b"test")
try:
record_metadata = future.get( timeout=10)
except KafkaError :
log.exeption()
pass
print( record_metadata.topic)
print(record_metadata.partition)
print(record_metadata.offset)
producer = KafkaProducer(value_serializer = lambda m: json.dumps(m).encode('ascii'))
producer.send('json-topic',{'key':'value'})
for _ in range (100):
producer.send('my-topic', b"test")
producer.send('my-topic',b"\xc2Hola, mundo!")
time.sleep(1)
So your question is how to run a python script? Simply save it, make executable and execute:
chmod +x ./kProducer.py
python ./kproducer.py
More detail are here: How to Run a Python Script via a File or the Shell
Add shebang line at the top to your script:
#!/usr/bin/env python-version
Replace the python-version with python2 for 2.x and python3 for 3.x
To check the version of python use the command:
python -V
The shebang line will determine the script ability to run as standalone. This will help when you want to double-click the script and execute it and not from the terminal. or simply say
python scriptname.py
I want to start a pythonscript by pushing a Button in a swift macOS application. I come up with:
let process = Process()
process.launchPath = "/usr/bin/python3"
process.currentDirectoryPath = "\(NSHomeDirectory())" + "/PycharmProjects/untitled5"
process.arguments = ["myscript.py"]
process.launch()
but I get "launch path not accessible" error by executing. If I change launchPath to:
process.launchPath = "/usr/bin/python"
everything works fine, but now I getting python compiling errors because myscript is written in python3.6.0, I have to use python3 because of using a library.
When I open Finder and go to "/usr/bin/python3" it says not found, but python3 is installed, I used it in Pycharm and I'm also able to start python3 in terminal.
In terminal "python3 ~/PycharmProjects/untitled5/myscript.py" works.
On your terminal type
which python3
this will return the path that is accessed when you run python3 from the command line
I've written this watchdog script to monitor VLC player and kill it when playback has stopped because VLC continues to inhibit the power management daemon after playback. The script works. I can run it from the command line or through IDLE and it kills VLC when playback stops. I've added many variations of the command to start the script to my startup applications as described here but when I reboot, if it is running at all, it stops as soon as VLC starts. Restarting it from a terminal cause it to stay running and do what it is supposed to do. I don't know if this is a problem with the script or something peculiar about Ubuntu Startup Applications (although I'm leaning towards Ubuntu). Maybe something to do with permissions? (Although I did chmod +x) Should I be executing some other commands to make sure DBus is up before I launch the script? Part of me thinks that something isn't fully loaded when the script starts so I tried sleeping before launching using the *nix sleep command, the X-GNOME-Autostart-Delay, and time.sleep(n) in the python code. The pythonic way seems to have the best chance of success. The *nix ways seem to only make startup take longer and at the end of it I find that the process isn't even running. I'm using the python-setproctitle module to name the process so I can quickly see if it is running with a ps -e from terminal. I'm out of ideas and about ready to just manually run the script whenever I reboot (although in principle I think that the machine should do it for me because I told it to). Some variations of Startup Application command lines that I've tried are:
/path/to/script/vlc_watchdog.py
"/path/to/script/vlc_watchdog.py"
/path/to/script/vlc_watchdog.py &
"/path/to/script/vlc_watchdog.py &"
python /path/to/script/vlc_watchdog.py
python /path/to/script/vlc_watchdog.py &
"python /path/to/script/vlc_watchdog.py"
"python /path/to/script/vlc_watchdog.py &"
bash -c "/path/to/script/vlc_watchdog.py"
sleep 30 ; /path/to/script/vlc_watchdog.py
sleep 30 && /path/to/script/vlc_watchdog.py
etc...
Full script:
#!/usr/bin/env python
import time
time.sleep(30)
import dbus
import os
import subprocess
from subprocess import Popen, PIPE
import daemon
import setproctitle
setproctitle.setproctitle('VLC-Watchdog')
sleeptime = 5
def vlc_killer():
bus = dbus.SessionBus()
vlc_media_player_obj = bus.get_object("org.mpris.MediaPlayer2.vlc", "/org/mpris/MediaPlayer2")
props_iface = dbus.Interface(vlc_media_player_obj, 'org.freedesktop.DBus.Properties')
pb_stat = props_iface.Get('org.mpris.MediaPlayer2.Player', 'PlaybackStatus')
if pb_stat == 'Stopped':
os.system("kill -9 $(pidof vlc)")
else:
time.sleep(sleeptime)
def vlc_is_running():
ps = subprocess.Popen(['ps', '-e'], stdout = PIPE)
out, err = ps.communicate()
for line in out.splitlines():
if 'vlc' in line:
return True
return False
def run():
while True:
if vlc_is_running():
vlc_killer()
else:
time.sleep(sleeptime)
with daemon.DaemonContext():
run()
In the shell script that starts your Python code (the one in the Ubuntu startup/initialization process), use something like:
#!/bin/sh
set -x
exec > /tmp/errors.out 2>&1
/path/to/script/vlc_watchdog.py
Then after things go awry again (that is, after another reboot), inspect /tmp/errors.out to see the error messages related to whatever happened. There should be a Python traceback in there, or at least a shell error.