Python Forum

Full Version: Regarding import library in two different program file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I wrote two Python programs. One program has a class definition and other program importing that class to access its attributes and methods. In both the programs I am importing sys in-built library and using it. Is there any way to import sys library in one program and use it in other program without importing?

Code is here:
#Program: program_1.py
import sys

class xmlFile:
    def sendXML(self, xmlFile):
        try:
            print("Processing XML file %s..." %xmlFile)
        except FileNotFoundError:
            print(os.path.basename(sys.argv[0])
                  + "->" + self.__class__.__name__
                  + "::"
                  + sys._getframe().f_code.co_name
                  + "(): File "
                  + xmlFile
                  + " does not exists!")
            exit(-2)

#Proram: program_2.py
import sys
import os.path
from program_1 import xmlFile

if (len(sys.argv) <= 1):
    print("usage: "+(os.path.basename(sys.argv[0]))+" <xml file>")
    exit

xmlFl = xmlFile()
dataList = xmlFl.sendXML(sys.argv[fl])
Thanks!
Why do you import it in program1 when you don't use it?
Sorry, I forgot to write a piece of code. Now it is corrected in the post.
short answer to your question - if you want to use a module like this (in this case sys) you need to import it in both modules.

Now, the design of you class is another matter. You handle the exception within the class, print some message that include the caller script, class, method and exit with sys.exit(). Many would compare with you slamming the door behind you. Note that all of this info is either known to the caller (i.e. the user of the class or is available in the traceback). So in fact you just print shorter version of the script, possibly omitting some intermediate steps/info that may be helpful to debug.

compare
Output:
bar.py->xmlFile::sendXML(): File spam1.xml does not exists!
with
Error:
Traceback (most recent call last): File "bar.py", line 10, in <module> dataList = xmlFl.sendXML(sys.argv[1]) File "foo.py", line 8, in sendXML open(xmlFile) FileNotFoundError: [Errno 2] No such file or directory: 'spam1.xml'
for example in your message it's not clear on which line exactly the error occur. What if it is some more complex method/function? yes, you can make your msg more specific. My point is that more proper way to do it is to leave the exception propagate to the caller. Then the caller should/would if they want handle it graciously and either continue or exit in some way. Imagine the caller need to do some cleaning like revert INSERT/UPDATE DB operation.

As a side note, you may want to use more pythonic way to create strings like f-strings or str.format() method, not the old style using % or concatenation.