0

I have been trying to change the system time on an offline Raspberry Pi 4 manually from a Python script that receives the time from a TCP client in the form of a string. As required by my project, the time will be need to be adjusted regularly from an input string. Below is the function I have tried using:

import subprocess

def timechange(time):
    cmd = ['exec sudo date +%T -s ' + str(time)]
    proc = subprocess.Popen(cmd, shell=True)
    proc.kill()

newtime = "13:00:00"
timechange(newtime)

However, I can't seem to consistently get this to change the time successfully using the above function. I have tried using os.open/subprocess.call instead but from other question responses, it seems that using os is not recommended.

All this function needs to do is to change the system time. Does the subprocess automatically exit and close the shell after the command finishes?

Being a beginner, I am not sure if it has to do with the termination of the shell/cmd or if it spawns too many shells. Any help will be much appreciated!

  • 1
    Why the `exec`? – Klaus D. Jan 06 '21 at 06:49
  • @KlausD. I saw in some other response that the exec in front helps to kill the shell process and the command. It was the second highest answer. https://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true – shenymer Jan 06 '21 at 06:53
  • 1
    That also explains the `kill()` which is most likely killing your command before it completed. The question you linked is about something very different. – Klaus D. Jan 06 '21 at 06:58
  • @KlausD. I see... Sorry i dont really know much about subprocesses. How should I code it such that it does not kill/terminate the process before it completes? – shenymer Jan 06 '21 at 07:02
  • 1
    Why don't you read the python official documentation on the subprocess module? – user202729 Jan 06 '21 at 07:04
  • You're killing the subprocess prematurely. Try using `proc.communicate()` instead of `proc.kill()` – prithajnath Jan 06 '21 at 07:05
  • @prithajnath wow that worked like a charm! Thank you so much! – shenymer Jan 06 '21 at 07:14
  • @user202729 Theres alot of information to go through, but I am working on it! just needed some help to point me where to look at. Thanks tho! – shenymer Jan 06 '21 at 07:14
  • 1
    Perhaps either run() or call(). They have a "common usage" section. in the docs, i think. – user202729 Jan 06 '21 at 07:15

0 Answers0