Python Forum
When I import a Module it wont run
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
When I import a Module it wont run
#11
just remove this if __name__ == '__main__': and adjust the indentations
this line is redundant if you are not going to run the module as stand alone script. I don't know if it resolve your problem (I didn't look into details) but as is it will cause problem when function is imported

To get understanding of what if __name__ == '__main__': is doing compare

module1:
def foo():
    print('This is print from inside function foo')
foo()
module2:
def foo():
    print('This is print from inside function foo')

if __name__ == '__main__':
    foo()
run and import each of the two modules to see the difference
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#12
I posted previously without reading your reply.
This is what Ive now done
import os
import globalVariables as gv

def listCWD():
    """ This section lists everything in the current working directory

    the if condition means that the code beneath it will only run if this file(__name__) is the Main Module(__main__)
    e.g it will not run if this module has been imported into another module. """
   

    try:
      gv.directoryList = os.listdir(gv.directoryIn)
      print('directoryList =\n',gv.directoryList)

    except FileNotFoundError:
      print('FileNotFoundError:\na List for the Directory gv.directoryIn cannnot be created\nbecause the Global Variable gv.directoryIn is an empty string.\n'
                      'To correct this either:\na)run the returnCWD function in this Module to assign a directory to gv.directoryIn or\nb)open the globalVariables.py file and setgv.directoryIn to = None')

    except TypeError:
      print('TypeError:\na List for the Directory gv.directoryIn cannnot be created\nbecause the Global Variable gv.directoryIn has been assigned to equal either:\n'
                     'a)List\nb)Set\nc)Tuple\n'
                     'To correct this either:\na)run the returnCWD function in this M odule to assign a directory to gv.directoryIn or\nb)open the globalVariables.py file and setgv.directoryIn to = None')

    except NameError:
      print('NameError:\nbecause of the Syntax Error on import a NameError now occurs in the functions code\n'
               'To correct the SyntaxError above open the globalVariables.py file and do either of the solutions below\n'
               'a)make directoryIn = an empty string\nb)make directoryIn = None')

listCWD()

if __name__ == '__main__':
    listCWD()
However after running the returnFileList Module I now get the following result which is including the FileNotFoundError that would otherwise be found if the listCwd.py Module was run on its own. I hope ive expalined that correctly.
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
 RESTART: G:\2 Employment and Education\2 Education\2 Projects(All)\6 My Python Projects\MyPyProject\FileManagerProgram\1 Successfuly Tested\3 Working on - need to steeamline(22 09 19 9pm)\For Qs on Python Forum\returnFileList.py 
The os module has been imported
The globalVariables module has been imported
The returnCWD module has been imported
FileNotFoundError:
a List for the Directory gv.directoryIn cannnot be created
because the Global Variable gv.directoryIn is an empty string.
To correct this either:
a)run the returnCWD function in this Module to assign a directory to gv.directoryIn or
b)open the globalVariables.py file and setgv.directoryIn to = None
The listCWD module has been imported

The Current Working Directory is
 G:\2 Employment and Education\2 Education\2 Projects(All)\6 My Python Projects\MyPyProject\FileManagerProgram\1 Successfuly Tested\3 Working on - need to steeamline(22 09 19 9pm)\For Qs on Python Forum

returnCWD ran corrrectly

directoryList =
 ['globalVariables.py', 'listCWD.py', 'returnCWD.py', 'returnFileList.py', '__pycache__']
listCWD ran corrrectly
Reply
#13
(Oct-14-2019, 12:23 PM)PyNovice Wrote: Ive just tried it this way

No, you didn't try it that way. What I suggested was this:

def foo():
    print(bar)
 
if __name__ == '__main__':
    foo()
That way has the function definition is outside the if __name__ block, and the function call is inside of it. You did this:

if __name__ == '__main__':
    def foo():
        print(bar)
 
foo()
You did the exact opposite. You put the function definition inside the if __name__ block, and the function call outside of it.

Whatever you put in the if __name__ block will NOT run when imported. At all. In any form. Ever. So in your version, when you import the code, the function is never defined. Then you try to call a function you didn't define, which necessarily causes an error.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#14
(Oct-14-2019, 12:45 PM)ichabod801 Wrote:
(Oct-14-2019, 12:23 PM)PyNovice Wrote: Ive just tried it this way

No, you didn't try it that way. What I suggested was this:

def foo():
    print(bar)
 
if __name__ == '__main__':
    foo()
That way has the function definition is outside the if __name__ block, and the function call is inside of it. You did this:

if __name__ == '__main__':
    def foo():
        print(bar)
 
foo()
You did the exact opposite. You put the function definition inside the if __name__ block, and the function call outside of it.

Whatever you put in the if __name__ block will NOT run when imported. At all. In any form. Ever. So in your version, when you import the code, the function is never defined. Then you try to call a function you didn't define, which necessarily causes an error.

Ive since corrected it. Read post 12
Heres a link to the updated files https://1drv.ms/u/s!AgNGJplI2Q3rgYhtqQ8o...A?e=qC2tyj
Reply
#15
you still don't get it. let's break the code in post 12

lines 1-2: here you import necessary modules. you want this part to be executed always (i.e. when import module or when execute as standalone script)

lines 4-27: this is the function definition. you want this part to be executed always (i.e. when import module or when execute as standalone script)

line 29: you executed listCWD() function. Again, this part to be executed always (i.e. when import module or when execute as standalone script), however is it what you want? Do you want to execute listCWD() AT THE TIME WHEN YOU IMPORT THE MODULE?

line 31-32: the if __name__ == '__main__': part, the body (line 32 and others if there were others) will be executed only when you execute the script as standalone. Line 32 will not be executed if you import module.

To sum up - remove line 29
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#16
(Oct-14-2019, 03:28 PM)buran Wrote: you still don't get it. let's break the code in post 12

lines 1-2: here you import necessary modules. you want this part to be executed always (i.e. when import module or when execute as standalone script)

lines 4-27: this is the function definition. you want this part to be executed always (i.e. when import module or when execute as standalone script)

line 29: you executed listCWD() function. Again, this part to be executed always (i.e. when import module or when execute as standalone script), however is it what you want? Do you want to execute listCWD() AT THE TIME WHEN YOU IMPORT THE MODULE?

line 31-32: the if __name__ == '__main__': part, the body (line 32 and others if there were others) will be executed only when you execute the script as standalone. Line 32 will not be executed if you import module.

To sum up - remove line 29
Thanks Buran thats very clear. I had included listCWD() in order to test the function in the listCWD.py Module but forgot to remove it. Should I include return at the end of the function after removing listCWD?
Reply
#17
(Oct-14-2019, 04:33 PM)PyNovice Wrote: I had included listCWD() in order to test the function in the listCWD.py Module but forgot to remove it.
That is what line 32 would do - it will be executed when you run the module as a script, but not when you import

(Oct-14-2019, 04:33 PM)PyNovice Wrote: Should I include return at the end of the function after removing listCWD?
It depends what you want it to do. Generally it would be considered better if the function has no side effects like printing. If you want a function to print the content of cwd then it's ok not to return anything (this will return implicitly None). On other hand you may return the content without printing it thus making the function more "universal" - e.g. in other cases you may want to use what it return instead of just printing it
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#18
Sorry for the late reply. Ive been away from my laptop for almost 2 weeks.

Thanks to all who helped me out. I appreciate you taking the time to help out.
The code now works. Ive added each Module below in case someone wants to use this or just to check it out. I didnt want to provide a link to my folder in onedrive in case I deleted that folder later and then people would not be able to access it.

The globalVariables.py Module
""" the directoryIn must not be left unassigned(blank)
This is because syntax errors will occur when this file is imported
The directoryIn variable must be created like either option below
a) directoryIn = ' '
or
b) directoryIn = None
or
c) use os.PathLike  Im not familiar with this method so i use the other two above
"""
directoryIn = ' '

"""
the directoryList variable can be a List or Tuple
use a List [] if you want to have the option of changing the returned data later
use a Tuple () if you want the returned data to be fixed
"""
directoryList =[]

""" the default directory should not be changed as it is python folder in idle"""
defaultDirectory = r'C:\Users\Me\AppData\Local\Programs\Python37-32'
The returnCWD.py Module
import os
import globalVariables as gv

def returnCWD():
    """ This section returns the current working directory"""
    gv.directoryIn = os.getcwd()
    print('The Current Working Directory is\n',gv.directoryIn)
The listCWD.py Module
import os
import globalVariables as gv

""" the  commented out code below is an example of how to catch synatx errors on import.
It attempts to import the file globalVariables.
There is a chance globalVariables.py can gie a syntax error if
a globalVariable has not been assigned any value by mistake
Therefore this try block could be used, however it is potentially dangerous to do so
read this article on the dangers of catching syntax errors https://airbrake.io/blog/python-exception-handling/python-syntaxerror"""
##try:
##    import globalVariables as gv
##except SyntaxError:
##    print('SyntaxError:\na List for the Directory gv.directoryIn cannnot be created\nbecause the Global Variable gv.directoryIn has not been assigned any value.\n'
##          'To correct this open the globalVariables.py file and do either of the solutions below\na)make directoryIn = an empty string\nb)make directoryIn = None')

def listCWD():
    """ This function lists everything in the current working directory """

    try:
      gv.directoryList = os.listdir(gv.directoryIn)
      print('The directoryList variable now contains\n',gv.directoryList)

    except FileNotFoundError:
      print('FileNotFoundError:\na List for the Directory gv.directoryIn cannnot be created\nbecause the Global Variable gv.directoryIn is an empty string.\n'
                      'To correct this either:\na)run the returnCWD function in this Module to assign a directory to gv.directoryIn or\nb)open the globalVariables.py file and setgv.directoryIn to = None')

    except TypeError:
      print('TypeError:\na List for the Directory gv.directoryIn cannnot be created\nbecause the Global Variable gv.directoryIn has been assigned to equal either:\n'
                     'a)List\nb)Set\nc)Tuple\n'
                     'To correct this either:\na)run the returnCWD function in this M odule to assign a directory to gv.directoryIn or\nb)open the globalVariables.py file and setgv.directoryIn to = None')

    except NameError:
      print('NameError:\nbecause of the Syntax Error on import a NameError now occurs in the functions code\n'
               'To correct the SyntaxError above open the globalVariables.py file and do either of the solutions below\n'
               'a)make directoryIn = an empty string\nb)make directoryIn = None')
    return


#  the if condition means that the code beneath it will only run if this file(__name__) is the Main Module(__main__)
#  eg it will not run if this module has been imported into another module. """
if __name__ == '__main__':
    listCWD()
The returnFileList.py Module
# This section Imports 4 different Modules"""
import os
print('The os module has been imported')
import globalVariables as gv
print('The globalVariables module has been imported')
import returnCWD as cwd
print('The returnCWD module has been imported')
import listCWD
print('The listCWD module has been imported')

print()

# This section runs the cwdFunction that is in the returnCWD Module. It returns the current working directory
cwd.returnCWD()
print('The returnCWD Function ran correctly')
print()

# This section assigns the listCWD function from the listCWD Module to a Variable named whatever and runs the function
whatever = listCWD.listCWD()
print('The Variable containing the listCWD Function ran correctly')
print()
print('All Items in the Current Working Directory are printed below:')
for items in gv.directoryList:
    print(items)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  is import cointegration_analysis a recognized module mitcht33 1 424 Nov-06-2023, 09:29 PM
Last Post: deanhystad
  Why wont this path work one way, but will the other way? cubangt 2 666 Sep-01-2023, 04:14 PM
Last Post: cubangt
  problem in import module from other folder akbarza 5 1,380 Sep-01-2023, 07:48 AM
Last Post: Gribouillis
  can not import anaconda pandas module. PySpark pandas module is imported!! aupres 0 711 Aug-06-2023, 01:09 AM
Last Post: aupres
  import module error tantony 5 3,433 Dec-15-2022, 01:55 PM
Last Post: Lauraburmrs
  Import a module one step back of the path prathampatel9 1 1,065 Sep-21-2022, 01:34 PM
Last Post: snippsat
  Import a module for use in type hint? Milosz 0 1,478 Nov-08-2021, 06:49 PM
Last Post: Milosz
  Can't install nor import delorean module Tek 3 2,792 Oct-27-2021, 03:32 AM
Last Post: Tek
  import module with syntax error Skaperen 7 5,253 Jun-22-2021, 10:38 AM
Last Post: Skaperen
  'urllib3' Module not found when import 'requests' spanz 5 10,156 Jan-06-2021, 05:57 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020