1

I wanna pass 2 arguments, one as list [8, 10], and one as integer in terminal. file MySeq.py

like: MySeq.py [8, 10], 32 How would i do this?

import sys

class MySeq():
def __init__(self, positions, length):
    self.positions = positions  
    self.length = length


def length_fragments(self):
    diffs = []

    diffs.append(self.positions[0])
    for i in range(1, len(self.positions)):
        diffs.append((self.positions[i] - self.positions[i - 1]))
    diffs.append(self.length - self.positions[len(self.positions) - 1])

    return diffs

#positons = sys.argv[1].replace('[', ' ').replace(']', ' ').replace(',', ' ').split()
#positions = [int(i) for i in a]
#length = int(sys.argv[2])
print(MySeq(positions, length).length_fragments())

2 Answers2

1

A way will be to pass arguments like this:

$ python filename.py 30 50 13

And code like this:

import sys
int_arg = int(sys.argv[-1])
list_from_args = list(sys.argv[1:-1])
for i in range(len(list_from_args)):
    list_from_args[i] = int(list_from_args[i])

This would mean that the args 30 50 will be converted into a python list object (that contains int) and the last argument ( 13 in this case ) will be treated as a int.

zoomlogo
  • 173
  • 4
  • 14
0

run

python MySeq.py 8,10 32

Since sys.argv is automatically a list of string, just use comma and split it to become a list.

def __init__(self):
        self.positions = sys.argv[1].split(',') # 8,10 to ['8', '10']
        self.length = int(sys.argv[2]) # 32
bonifacio_kid
  • 633
  • 5
  • 8
  • sorry, its not entirely clear to me how to i would need to edit my code: `class MySeq():` `def __init__(self):` ` self.positions = sys.argv[1].split(',') # 8,10 to ['8', '10']` ` self.length = int(sys.argv[2]) # 32` – pythonabsir Dec 04 '20 at 06:43
  • + how would I need to edit my code for a terminal input such as: `python MySeq.py [8, 10] 32` – pythonabsir Dec 04 '20 at 06:54