Ask Your Question
2

How can I use sudo to initiate and terminate a Python script within another Python script?

asked 2023-05-25 22:28:22 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
3

answered 2023-05-25 22:41:02 +0000

david gravatar image

To initiate a Python script using sudo within another Python script, you can use the subprocess module. Here’s an example code:

import subprocess

# initiate the script using sudo
command = ['sudo', 'python', '/path/to/script.py']
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()

# check the output and error message
if error:
    print(error.decode())
else:
    print(output.decode())

To terminate the Python script initiated using sudo, you can use the pidof command and kill the process. Here’s an example code:

import os

# kill the process using pidof
command = 'sudo pidof python /path/to/script.py | xargs sudo kill -9'
os.system(command)

Note that killing a process using -9 option is a forceful shutdown which can cause data loss. It is recommended to use a more graceful method to terminate a process wherever possible.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-25 22:28:22 +0000

Seen: 10 times

Last updated: May 25 '23