Run Python Script Automatically at Startup - Ubuntu 16.04 - python

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 #

Related

python http server hide console

I am trying to do a script that is hosting my file on my local network, here's my code :
import os
import getpass
os.system('python -m http.server --directory C:/Users/'+getpass.getuser())
But the probleme is that the http console is showing on my Desktop and that's annoying ! so I tried to hide by renaming the file in .pyw but it's not working.
Have you any idea on how to hide this console ? Thank you :D
On Linux you can use Nohup to ignore the HUP signal.
You could add nohup on your code like this:
import os
import getpass
os.system('nohup python -m http.server --directory C:/Users/'+getpass.getuser())
Update
Solution for windows
import os
import subprocess
import getpass
env = os.environ
directory = 'C:/Users/'+getpass.getuser()
proc = subprocess.Popen(['python', '-m', 'http.server', '--directory', directory], env=env)
Assuming you're on Linux (or other unix based OS), you can detach the process from the console after starting the server.
Here is one way to do it with screen command
sudo apt install -Y screen
And then
screen -d -m "python3 script.py"
Where script.py is the snippet you have shared.
Reference for the flags
...
-d -m
Start screen in detached mode. This creates a new session but doesn’t attach to it. This is useful for system startup scripts.
I found a way to do it, with a VBS script:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "main.py" & Chr(34), 0
Set WshShell = Nothing
Just replace main.py with the path of your script.

How do I use Python to launch an interactive Docker container?

I am working with a Docker image which I launch in interactive mode like so: docker run -it --rm ubuntu bash
The actual image I work with has many complicated parameters, which is why I wrote a script to construct the full docker run command and launch it for me. As the logic grew more complicated, I want to migrate the script from bash to Python.
Using docker-py, I prepared everything to run the image. Seems like using docker.containers.run for interactive shells is not supported, however. Using subprocess instead seems logical, so I tried the following:
import subprocess
subprocess.Popen(['docker', 'run', '-it', '--rm', 'ubuntu', 'bash'])
But this gives me:
$ python3 docker_run_test.py
$ unable to setup input stream: unable to set IO streams as raw terminal: input/output error
$
Note that the error message appears in a different shell prompt from the python command.
How do I make python3 docker_run_test.py to do equivalent of running docker run -it --rm ubuntu bash?
You can use a pseudo-terminal to read from and write to the container process
import pty
import sys
import select
import os
import subprocess
pty, tty = pty.openpty()
p = subprocess.Popen(['docker', 'run', '-it', '--rm', 'ubuntu', 'bash'], stdin=tty, stdout=tty, stderr=tty)
while p.poll() is None:
# Watch two files, STDIN of your Python process and the pseudo terminal
r, _, _ = select.select([sys.stdin, pty], [], [])
if sys.stdin in r:
input_from_your_terminal = os.read(sys.stdin.fileno(), 10240)
os.write(pty, input_from_your_terminal)
elif pty in r:
output_from_docker = os.read(pty, 10240)
os.write(sys.stdout.fileno(), output_from_docker)
Can we use this ?
import os
os.system('docker run -it --rm ubuntu bash')

Python - Executing shell command does not work on Linux

I like to run a shell command from Python on my Linux Mint system.
Specifically the command runs all Bleachbit cleaners and works perfectly
fine when run maually.
Yet, trying to run the same command via the subprocess.call module
always results in an exception raised.
I just can not see why it should not work.
The command does not require sudo rights, so not requiring
right not given.
I also have firefox/browsers closed when executing the python command.
Anybody, any suggestions how to fix this issue?
My code:
try:
subprocess.call('bleachbit -c firefox.*')
except:
print "Error."
subprocess module does not run the shell by default therefore the shell wildcards (globbing patterns) such as * are not expanded. You could use glob to expand it manually:
#!/usr/bin/env python
import glob
import subprocess
pattern = 'firefox.*'
files = glob.glob(pattern) or [pattern]
subprocess.check_call(["bleachbit", "-c"] + files)
If the command is more complex and you have full control about its content then you could use shell=True to run it in the shell:
subprocess.check_call("bleachbit -c firefox.*", shell=True)
When shell is False you need to pass a list of args:
import subprocess
try:
subprocess.call(["bleachbit", "-c","firefox.*"])
except:
print ("Error.")

Calling a subprocess in python with environmental variables

I am trying to write a python script to automatically scan a section of plex using the Plex Media Scanner. To do so, I must run the scanner as the user running plex (in this case it is 'plex') as well as provide it with the environment variable 'LD_LIBRARY_PATH'. I've tried using both subprocess.call and subprocess.Popen with no difference. In either case, I am not getting any output.
Here is the code I am using:
#!/usr/bin/python
import os
import subprocess
import shlex
env = os.environ.copy()
env['LD_LIBRARY_PATH'] = '/usr/lib/plexmediaserver'
s = "/bin/su - plex -c '/usr/lib/plexmediaserver/Plex\ Media\ Scanner -s -c 2'"
task = shlex.split(s)
exitCode = subprocess.call(task, env=env, shell=True)
Now I already have a working version that does what I want it to do but I had to resort to using a wrapper bash script to do so. You can see the code below:
#!/bin/sh
export LD_LIBRARY_PATH=/usr/lib/plexmediaserver
/usr/lib/plexmediaserver/Plex\ Media\ Scanner $#
And the relevant line of the script which calls it:
exitCode = subprocess.call("/bin/su - plex -c '/var/lib/deluge/delugeScripts/pms.sh -s -c 2'", shell=True)
Thanks for your help.
As jordanm noted in his comment:
the - in su makes it a login shell which re-initializes the environment.

processing output of time command in a python script

I am trying to write a python script that benchmarks several pieces of code. The issue is when the script is run the output of the command id different from what I would get it I run it directly at bash prompt.
Here is the code for the python script
import subprocess
import re
import os
app = os.getcwd() + "/" + "myapp"
testPopen = subprocess.Popen(args=['/usr/bin/time',app],
stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=False)
testPopen.wait()
Here is the ouput of above code
real 1.0
user 0.8
sys 0.0
When you run time myapp from the bash prompt, you are using bash's time command. (Type help time to see that bash understands it as a bash command.)
When you run the python script you are using /usr/bin/time, which is a different program. (Type man time or which time to see that time is also a program. How confusing!)
To get the python script to use the bash time command:
import shlex
testPopen = subprocess.Popen(shlex.split('bash -c "time {a}"'.format(a = app)),
stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=False)
out,err = testPopen.communicate()
print(err)

Categories

Resources