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
#1
Hello, I have 4 files. They are:

globalVariables.py - this stores variables that are used in other modules
returnCWD.py - this has a function that returns the current working directory
listCWD - this has a function that prints a list of all items within the current working directory
returnFileList - this file imports the 3 files above and runs the function from returnCWD.py and
the function from listCWD.py

My problem
In order to import the listCWD module I had to add this piece of code
if __name__ == '__main__':
to the listCWD function in the listCWD.py file to prevent the listCWD.py file from running on import
but this code then prevents me from calling the listCWD function.

Can anyone help with this. I have attached a url link to the files.
My 4 python files within a folder

Thanks in advance to anyone who takes the time to help out.
Reply
#2
If the listCWD function definition is not in the if __name__ block, you should be able to run it like this:

import listCWD
whatever = listCWD.listCWD()
Remember, you want the definition outside the if __name__ block, and the actual call to it inside the if __name__ block.

If that does not solve your problem, please post some just enough runnable code to replicate the error, along with the full text of any error message.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(Sep-22-2019, 06:32 PM)ichabod801 Wrote: If the listCWD function definition is not in the if __name__ block, you should be able to run it like this:

import listCWD
whatever = listCWD.listCWD()
Remember, you want the definition outside the if __name__ block, and the actual call to it inside the if __name__ block.

If that does not solve your problem, please post some just enough runnable code to replicate the error, along with the full text of any error message.

Thanks for your reply. i tried what you said above but I got the error message below. i have added a url for all the files to my first post. im not an experienced coder and cant replicate the error with a smaller piece of code.

Traceback (most recent call last):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\returnFileList.py", line 19, in <module>
    whatever = listCWD.listCWD()
AttributeError: 'function' object has no attribute 'listCWD'

(Sep-22-2019, 06:32 PM)ichabod801 Wrote: If the listCWD function definition is not in the if __name__ block, you should be able to run it like this:

import listCWD
whatever = listCWD.listCWD()
Remember, you want the definition outside the if __name__ block, and the actual call to it inside the if __name__ block.

If that does not solve your problem, please post some just enough runnable code to replicate the error, along with the full text of any error message.

I forgot to alter the import statement last time so i tried what you recommended again and it has imported correctly and the function was called but it hasnt returned what i wanted. The output is below. The current working directory was returned but you will notice that the list of items in the directory did not print.

The os module has been imported
The globalVariables module has been imported
The returnCWD module has been imported
The listCWD module has been imported

The Current Working Directory is
 C:\Users\Me\AppData\Local\Programs\Python\Python37-32

returnCWD ran corrrectly

listCWD ran corrrectly
Reply
#4
Okay, but the module seems to be importing correctly, so this seems to be a problem with the listCWD function.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
(Sep-22-2019, 06:59 PM)ichabod801 Wrote: Okay, but the module seems to be importing correctly, so this seems to be a problem with the listCWD function.

Here is the code in the listCWD.py file
import os
import globalVariables as gv 

def listCWD():
        
        if __name__ == '__main__':  
        
        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()
Reply
#6
First of all, that is not the correct code or you would be getting an indentation error. Second, the if __name__ goes at the end of the file, and is only for code that should not be run when the file is imported. If you stick it in the middle of a function, the function won't do anything when it is imported.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#7
(Sep-23-2019, 01:06 AM)ichabod801 Wrote: First of all, that is not the correct code or you would be getting an indentation error. Second, the if __name__ goes at the end of the file, and is only for code that should not be run when the file is imported. If you stick it in the middle of a function, the function won't do anything when it is imported.

I'm out of the house atm so I'll reply properly later when I can check the code.
Reply
#8
(Sep-23-2019, 01:06 AM)ichabod801 Wrote: First of all, that is not the correct code or you would be getting an indentation error. Second, the if __name__ goes at the end of the file, and is only for code that should not be run when the file is imported. If you stick it in the middle of a function, the function won't do anything when it is imported.

Sorry about the late reply but Ive been a way for the last 2 weeks.
When I pasted the previous code it didnt display the way I wanted. The actual code I used is below:
import os
import globalVariables as gv 
 
def listCWD():
         
    if __name__ == '__main__':  
         
        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()
You say that the if main code should go at the end of the file but I dont have anything to put after the if main piece of code. The file listCWD.py only contains a listCWD function and if I dont use If main the function runs on Import and I do not want it to run on import.
Reply
#9
If you do it this way:

def foo():
    if __name__ == '__main__':
        print('bar')

foo()
The print statement will not run if the function is imported. The function is called when imported (line 5), but since the print is suppressed, it looks like nothing is happening. But then if you call it from the module that did the import, nothing will happen then either, because the if statement is suppressing the print statement.

This is what you usually do:

def foo():
    print(bar)

if __name__ == '__main__':
    foo()
Now if you import the file, the function is not called at all, because the last line is suppressed by the if statement. But if the module that does the importing calls the foo function, the print works, because it is no longer being suppressed by the if statement.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#10
Ive just tried it this way but I get the error message at the bottom of the page when I run the returnFileList.py Module.
import os
import globalVariables as gv

if __name__ == '__main__':

   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()
Error Message:
Traceback (most recent call last):
File "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", line 7, in <module>
import listCWD
File "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\listCWD.py", line 43, in <module>
listCWD()
NameError: name 'listCWD' is not defined


This is the code from theReturnFileList Module that gave the error message.
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()

cwd.returnCWD()
print('returnCWD ran corrrectly')
print()

# this function is running but not doing what i want
# that is because of the if name = main condition in the functions code
# i need to fix this
whatever = listCWD.listCWD()
print('listCWD ran corrrectly')
Reply


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