1

How can I append URLs to a array in python, I was trying using the following code,

zone = ["z1", "z2", "z3"]
result_1 = []

for i in zone:
    result_val = os.system("gcloud command1 " +i+ " --command2")
    result_1.append(result_val)
print(result_1)

But when run this, my results are printing like below,

https://sample-domain.com/test/abc/1
https://sample-domain.com/test/abc/2
https://sample-domain.com/test/abc/3

But when I print the "result_1" it shows me below result

[0, 0, 0]

But I need the result like this,

["https://sample-domain.com/test/abc/1","https://sample-domain.com/test/abc/2","https://sample-domain.com/test/abc/3"]

How can I correct this issue ?

Any help would be greatly appreciated.

Thanks.

baduker
  • 19,152
  • 9
  • 33
  • 56
Madura Dissanayake
  • 8,309
  • 5
  • 25
  • 34
  • What's the exact command you're running there? The result is the exit error (0) that you add to the list. – baduker Jul 01 '22 at 08:14
  • @baduker I get `512` as result, instead of a link – Cardstdani Jul 01 '22 at 08:14
  • 1
    There is nothing wrong with the code to append to append to your list (we don't call it an array). The problem is that `result_val` is not the string that is printed by the command you are running - the output has **nothing to do with** the `os.system` function, just like how `print` and `return` have nothing to do with each other. Please see https://stackoverflow.com/questions/4760215 (I am out of duplicate close votes for today). – Karl Knechtel Jul 01 '22 at 08:16

2 Answers2

1

You need to store in your list the standard output.
What you are doing now is only storing the return code.

It is possible to obtain a similar result using Popen from subprocess.

import subprocess

zone = ["z1", "z2", "z3"]
result_1 = []

for i in zone:
    proc = subprocess.Popen(["gcloud", "command1", i , "--command2"], stdout=subprocess.PIPE)
    for line in iter(proc.stdout.readline, ''):
        result_1.append(line.rstrip())
print(result_1)
Pitto
  • 8,229
  • 3
  • 42
  • 51
-1

You may want to use .check_output from subprocess module, as the comments suggest, you need to get the output printed in the console, not the result of os.system(), which returns a different value:

import subprocess

zone = ["z1", "z2", "z3"]
result_1 = []

for i in zone:
    res = subprocess.check_output(["gcloud", "command1", i, "--command2"])
    result_1.append(res)
print(result_1)
tripleee
  • 175,061
  • 34
  • 275
  • 318
Cardstdani
  • 4,999
  • 3
  • 12
  • 31