Last active
January 5, 2019 18:43
-
-
Save LucasCoderT/124ba8465f41db5953972454a6682034 to your computer and use it in GitHub Desktop.
Creates systemd service for python scripts. Only tested for Ubuntu 16.04
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import subprocess | |
# SystemD service creator | |
## Creates a systemd service file and moves it to the appropriate location and enables it | |
system_service = """[Unit] | |
Description={description} | |
After=multi-user.target | |
[Service] | |
Type=simple | |
WorkingDirectory={working_dir} | |
ExecStart={python_path} {executable_path} | |
User={run_as} | |
Restart=on-failure | |
[Install] | |
WantedBy=multi-user.target | |
""" | |
system_path = "/etc/systemd/system/" | |
if __name__ == '__main__': | |
project_name = input("Enter Project Name:") | |
project_description = input("Enter Project Description:") | |
project_path = input("Enter Project Path:") | |
main_file = input("Enter Main File:") | |
python_path = sys.executable | |
user_name = input("Enter User to run as:") | |
service_file_name = "{}.service".format(project_name) | |
with open(service_file_name, "w+") as service_file: | |
service_file.writelines( | |
system_service.format(description=project_description, working_dir=project_path, python_path=python_path, | |
executable_path=main_file, run_as=user_name)) | |
try: | |
print("moving service to {}".format(system_path)) | |
subprocess.call(["sudo", 'cp', service_file_name, system_path]) | |
print("Registering service") | |
subprocess.call(["sudo", "systemctl", "daemon-reload"]) | |
print("Service registered") | |
print("Starting service") | |
subprocess.call(["sudo", "systemctl", "start", project_name]) | |
print("Enabling service on boot") | |
subprocess.call(["sudo", "systemctl", "enable", project_name]) | |
except: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment