Reputation: 821
I want to pass some data to another python script and do something there. But the data i send conflicts if i run script multiple times at the same time with different arguments. How do i separate them?
Example code:
main.py
import otherscript
list_a = [1,2,3] # from arguments
otherscript.append_to_another_list(list_a)
otherscript.py
another_list = []
def append_to_another_list(list):
another_list.append(list)
print(another_list)
if i run main.py twice at the same time with arguments 1,2,3 and 4,5,6 it prints both of them in the same list like [1,2,3,4,5,6]. I hope i made this clear
Upvotes: 1
Views: 3947
Reputation: 20490
I just simplified your main.py
as follows
import otherscript
import sys
list_a = [int(item) for item in sys.argv[1:]]
otherscript.append_to_another_list(list_a)
And then when I run them together using python3.7 main.py 1 2 3 && python3.7 main.py 4 5 6
I get the output
[[1, 2, 3]]
[[4, 5, 6]]
In addition, if you open the same terminal and run the append_to_another_list
command twice, the output will change, since you are referring to the same list!
In [2]: import otherscript
In [3]: otherscript.append_to_another_list([1,2,3])
[[1, 2, 3]]
In [4]: otherscript.append_to_another_list([4,5,6])
[[1, 2, 3], [4, 5, 6]]
Upvotes: 1
Reputation: 2764
Of you invoke this twice from the OS command line - say, bash
- you would expect them to be totally independent, not showing the behaviour the OP describes.
On the other hand, within a single Python interpreter, a module is only initialised the once, so the list in your otherscript
module (which is a module rather than a script) will stick around, and keep being appended to.
In any case, perhaps your best option for finer control would be a class.
class ListKeeper:
def __init__(self):
self.another_list = []
def append_to_another_list(self, list):
self.another_list.append(list)
print(another_list)
Your main.py
would look like:
import otherscript
list_a = [1,2,3] # from arguments
keeper1 = otherscript.ListKeeper()
keeper1.append_to_another_list(list_a)
You can create as many instances as you need, all independent of one another, and all keeping their own state.
Upvotes: 3