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 ?

4
  • Use list instead of formatted string to pass args stackoverflow.com/questions/14928860/… Commented Feb 17, 2021 at 14:36
  • @lllrnr101 If you think this question has an answer somewhere else in this site - flag it as duplicate instead of posting a link as a comment... Commented Feb 17, 2021 at 14:43
  • Try to print command_date.split() and see the problem... Commented Feb 17, 2021 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 Commented Feb 17, 2021 at 14:49

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.