2

I am trying to execute the following command from my python script, using subprocess :

date -s "25 DEC 2021 15:30:00"

This is how i am executing the command :

command_date = ("/usr/bin/date -s \"{0}\"".format(config_date))
print("command date : ",command_date)

proc = subprocess.Popen(command_date.split(), stdout = subprocess.PIPE, encoding = "utf8")
result_date = proc.stdout.read()
print("\nNew system date : ", result_date)

But i am getting the following error :

/usr/bin/date: extra operand '2021'

After some tests directly by the terminal, the error apprear if i am using the command without the quotes around the date string. But my variable command_date is well constructed (see print : /usr/bin/date -s "25 DEC 2021 15:30:00")

Do you know why my quotes are ignored and how to fix it ?

molik
  • 51
  • 5
  • Use list instead of formatted string to pass args https://stackoverflow.com/questions/14928860/passing-double-quote-shell-commands-in-python-to-subprocess-popen – lllrnr101 Feb 17 '21 at 14:36
  • @lllrnr101 If you think this question has an answer somewhere else in this site - [flag it as duplicate](https://stackoverflow.com/help/privileges/flag-posts) instead of posting a link as a comment... – Tomerikoo Feb 17 '21 at 14:43
  • Try to print `command_date.split()` and see the problem... – Tomerikoo Feb 17 '21 at 14:46
  • 1
    @Tomerikoo This is what i got : `['/usr/bin/date', '-s', '"25', 'DEC', '2021', '15:30:00"']`. I understand why it wasn't working now, thanks – molik Feb 17 '21 at 14:49

1 Answers1

1

The issue comes from calling split on the string, which splits the string at whitespaces into seperate arguments for date. Try to build the list of command + arguments yourself:

command = ["/usr/bin/date", "-s", "{0}".format(config_date)]
proc = subprocess.Popen(command, stdout = subprocess.PIPE, encoding = "utf8")
result_date = proc.stdout.read()
print("\nNew system date : ", result_date)
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53