Reputation: 373
Suppose I have a Zip file and test1.py
is taking the input of the Zip file from the user.
Now, test2.py
prints the contents of a Zip file.
I want to take the input Zip file from test1.py
for the operation of test2.py
.
So whenever I run the test1.py
, it should ask for the name of Zip file and forward it to the test2.py
and show the output of test2.py
.
I am trying to do it like this :
test1.py:
import zipfile
import os
inputzip = input("Enter the Zip File:")
file = zipfile.ZipFile(inputzip, "r")
os.system("py test2.py")
test2.py:
import zipfile
import os
print ("The list of files in the zip : ")
for name in file.namelist():
print (name)
But whenever I am going to run test1.py, it is always showing,
Enter the zip file:
test2.py is not executing. I am using python 3.x
Upvotes: 1
Views: 9936
Reputation: 2268
The commenters are right, but it sounds like you want to know anyway. The problem was already highlighted by @martineau. What is happening is the following:
Because they do not know about each other, the easiest option you have in the manner you want to do it (i.e., using os.system()), is to pass information from test1.py to test2.py in the form of a string. One way would be the following:
test1.py:
import zipfile
import os
inputzip = input("Enter the Zip File:")
files = zipfile.ZipFile(inputzip, "r")
name_list = (" ".join([i for i in files.namelist()]))
os.system("python3 test2.py {0}".format(name_list))
and
test2.py:
import zipfile
import sys
print ("The list of files in the zip : ")
for name in sys.argv[1:]:
print (name)
output:
Enter the Zip File:test.zip
The list of files in the zip :
test
txt1
txt2
In the end this is pretty messy and as already pointed out by @joelgoldstick, you should just import the method from test2.py into test1.py. For example:
test2.py:
def test2_method(zipfile):
print ("The list of files in the zip : ")
for name in zipfile.namelist():
print (name)
test1.py:
import zipfile
from test2 import test2_method
inputzip = input("Enter the Zip File:")
files = zipfile.ZipFile(inputzip, "r")
test2_method(files)
output:
Enter the Zip File:test.zip
The list of files in the zip :
test
txt1
txt2
I am currently wondering how easy it would be to have both processes share memory and one to be able to pass the memory reference of the opened zip file object to the other. Don't know if this is even possible >_<. Anyone who could enlighten would be cool.
Upvotes: 2