-1

In following code I am trying to append string 'timeout' as first element of list imput_cmd. To do this, I am using insert at 0th index of the list. but My print statement is always returning None. Can someone please point what I am missing here ?

import subprocess

def run_command(command,timeout):
    input_cmd = command.split()
    print(command)
    print(input_cmd)
    imput_cmd_with_with_timeout = input_cmd.insert(0,'timeout')
    print(imput_cmd_with_with_timeout)



run_command('sleep 60', 10)

I am using python 3.6

AMC
  • 2,642
  • 7
  • 13
  • 35
monk
  • 1,953
  • 3
  • 21
  • 41
  • 1
    @dawg The function's not supposed to return anything - really it's irrelevant. The problem is actually that `imput_cmd_with_with_timeout` is `None`. See narendra's answer. – wjandrea Apr 29 '20 at 00:43
  • Does this answer your question? [Why does append() always return None in Python?](https://stackoverflow.com/questions/16641119/why-does-append-always-return-none-in-python) – AMC Apr 29 '20 at 01:13
  • Read the [docs](https://docs.python.org/3.8/tutorial/datastructures.html#more-on-lists): "You might have noticed that methods like `insert`, `remove` or `sort` that only modify the list have no return value printed – they return the default `None`". – Gino Mempin Apr 29 '20 at 02:10

1 Answers1

3

list.insert adds to the same list. It doesn't return a new list.

To insert into a new list, you need to copy contents into a new list, and then call insert.

imput_cmd_with_with_timeout =  input_cmd[:]
imput_cmd_with_with_timeout.insert(0,'timeout') 
print(imput_cmd_with_with_timeout)
# ['timeout', 'sleep', '60']
narendra-choudhary
  • 4,582
  • 4
  • 38
  • 58
  • @dawg yes, agreed (+1)! But question is more focused on why `print(imput_cmd_with_with_timeout)` is outputting `None`. – narendra-choudhary Apr 29 '20 at 00:44
  • @dawg I am returning from the real function , this is a scaled down version of actual problem. I am using `imput_cmd_with_with_timeout` further in the same function. but due t o some reasons imput_cmd_with_with_timeout was None. – monk Apr 29 '20 at 00:44
  • FWIW, the clearer way to copy a list is `input_cmd.copy()`, but I think this would actually be clearest as `imput_cmd_with_with_timeout = ['timeout'] + input_cmd` – wjandrea Apr 29 '20 at 00:49
  • https://stackoverflow.com/questions/16641119/why-does-append-always-return-none-in-python – AMC Apr 29 '20 at 01:13