Skip to content
Advertisement

Literating list by for loop gives whole list instead of each element in list

the script needs two input arguments from sys.argv

$ python3 check_process.py mem_info.json "['192.168.24.9', '192.168.24.13', '192.168.24.22', '192.168.24.38']"

then those argv will pass to the parameter

nodes

nodes = sys.argv[2:]

I’m trying to iterate over each elements of nodes

if __name__ == "__main__":

    passed_args = len(sys.argv)
    filename = sys.argv[1]
    nodes = sys.argv[2:]

    for i in nodes:
        print("node:" + " " + i)

but it gives me the whole list

node: ['192.168.24.9', '192.168.24.13', '192.168.24.22', '192.168.24.38']

the thing I wanted is

node: '192.168.24.9'
node: '192.168.24.13'
node: '192.168.24.22'
node: '192.168.24.38'

Is there something to do with argv ? I’ve tried many ways but it doesn’t help

Advertisement

Answer

sys.argv is a list of strings. The fact that you’re passing a string that “looks like” a list is immaterial. The second element of argv is a single string containing the text ['192.168.24.9', '192.168.24.13', '192.168.24.22', '192.168.24.38']. You would need to parse that into a list.

The simpler solution, I think, is to pass the addresses on the command line as separate parameters:

$ python3 check_process.py mem_info.json 192.168.24.9 192.168.24.13 192.168.24.22 192.168.24.38

This way, each IP address will be a separate element of argv, and argv[2:] will return the list of nodes that you want.

If you can’t do that, you need to start with argv[2] as a single string and parse it into a list. Use the strip method to remove the square brackets, and use the split method to create the list.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement