Python Forum
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 3 Module Import Help
#1
Hi, I am currently creating a python scriot which will allow the user to achive different objectives depending upon which option they choose. I am however having an issue with custom modules as I have created an external script i.e. examplescript.py and i wish to have that run within my main python menu whenever someone choose option 1 on the menu but cyrrently at the top when I import the external script with:

Import examplescript

It simply runs the contents on the exterbal script straight away whenever the main python menu is started and I wondering if anyone knew how i get this script to only active when it is suppose to after a user has selected option 1 of the menu and not at any other time. Any help is greatly appreciated.

Thanks.
Reply
#2
if the __init__ method of the examplescript has a command to execute and method within the script, it will execute upon
instantiating the class of import, but not on the import itself

for example, given two modules (ModuleA and ModuleB), ModuleB will import ModuleA. In the example below, Module A executes methoda in the initialization routine, so upon instantiation will execute that method

ModuleA:
class ModuleA:
    def __init__(self):
        self.methoda()
    
    def methoda(self):
        print('This is methoda')

if __name__ == '__main__':
    ModuleA()
ModuleB:
import ModuleA


class ModuleB:
    def __init__(self):
        moda = ModuleA.ModuleA()

if __name__ == '__main__':
    ModuleB()
Now run ModuleB from command line:
Output:
(venv) > python ModuleB.py This is methoda (venv) >
If the call to execute methoda is removed from the __init__ method, it will not execute until called:

example:
ModuleA:
class ModuleA:
    def __init__(self):
        pass
    
    def methoda(self):
        print('This is methoda')

if __name__ == '__main__':
    ModuleA()
ModuleB:
import ModuleA


class ModuleB:
    def __init__(self):
        moda = ModuleA.ModuleA()
    
        input('Press enter to execute methoda of ModuleA')
        moda.methoda()

if __name__ == '__main__':
    ModuleB()
Now it only gets executed when told to do so:
Output:
(venv) > python ModuleB.py Press enter to execute methoda of ModuleA This is methoda (venv) >
Reply
#3
We'll have to see the code for examplescript to adequately assist. It sounds like the functions inside the module are being called or the module is a script itself without defined functions. Still, to help you correct it, we need to see it.
Reply
#4
Yeah, sorry i should of thought about including the files in my original post but here they are:

PythonMenu.py is my main python menu script

__________________________________________________________________________________________________________________________________________
#This is the main script for component 2 of Programming for System Administrators.
#CM3123.
#Author - Adam Nayler.
#Student Number - 1803974.
#Initial Creation Date - 26/10/2018.

#!/usr/bin/env python3

#The first line imports the ConnectHandler from netmiko to allow for secure SSH connections by the script.
#import os, imports the os module for the scripts use.
#import sys, imports the sys module for the scripts use.

from netmiko import ConnectHandler
import os
import sys
import RoutingConfigurationScript

#This is a function to introduce the script to the user. 
#'clear' will clear everythign off the screen that is currentely there to stop cluttering and increase tidyness.

def introduction():

	os.system('clear') #Clear Screen.
	print("\n\t\t\tWelcome to the assignment script for CM3123")
	print("\n\t\t\tCreated by Adam Nayler")
	print("\n\t\t\tStudent Number - 1803974")
	input("\n\t\t\t\tPlease press enter to begin the script")

	menu() 


#This is a function for the main scripts menu.

def menu():

	selection = ""
	while selection == "":
		os.system('clear') #Clear Screen.
		print("\n\n\n")
		print("\t\t\tPython3 Script By Adam Nayler\n\n\n")
		print("\t\t\tStudent Number - 1803974\n\n\n")
		print("\tPlease select a choice from the options below:\n\n")

		print("\t1. Remotely Configure a Routing Device. ")
		print("\t2. Remotely Configure a Switching Device. ")
		print("\t3. Open Up A Sub-menu For Comparing Different Configuration Files. ")
		print("\t4. Open Up A Sub-menu For Extracting Performance And Device Parameters From Different Network Devices. ")
		print("\t5. Capture And Output Network Traffic. ")
		print("\t6. Exit the Menu. ")

		
		selection = input("\n\tPlease select the option you wish to run: ")
		
		if selection == "1":
			ConfigureRoutingDevices()
		elif selection == "2":
			ConfigureSwitchingDevices()
		elif selection == "3":
			ComparisonMenu()
		elif selection == "4":
			ExtractingDataMenu()
		elif selection == "5":
			CaptureAndOutputTraffic()
		elif selection == "6":
			exit()

		else:
			os.system('clear') #Clear Screen.
			print("\n\n\n\t\t\tYou have entered and incorrect value. ")
			print("\n\t\t\tPress the enter key to return to the main menu. ")
			input ("")


#This is the function that connects to multiple routing devices and performs the required commands from the commands file.

def ConfigureRoutingDevices():
	print("1")

#This is the function that connects to multiple switching devices and performs the required commands from the commands file.

def ConfigureSwitchingDevices():
	print("2")

#Function to open up the sub-menu that will compare configuration files.

def ComparisonMenu():

	selection = ""
	while selection == "":
		os.system('clear') #CLear Screen.
		print("\n\n\n")
		print("\t\t\tThis Is The Sub-menu For Comparing Different Configuration Files\n\n\n ")
		print("\tPlease select a choice from the options below.\n\n ")

		print("\t1. Compare the running configuration and startup configuration of a routing device. ")
		print("\t2. Compare the running configuration of a routing device with an offline configuration. ")
		print("\t3. Compare the startup configuration of a routing device with an offline configuration. ")
		print("\t4. Exit back to the original menu. ")


		selection = input("\n\tPlease select the option you wish to run: ")
 
		if selection == "1":
			CompareRunningWithStartUpConfig()
		elif selection == "2":
			CompareRunningWithLocalConfig()
		elif selection == "3":
			CompareStartUpWithLocalConfig()
		elif selection == "4":
			menu()
		else:
			os.system('clear') #Clear Screen.
			print("\n\n\n\t\t\tYou have entered and incorrect value. ")
			print("\n\t\t\tPress the enter key to return to the main menu. ")
			input ("")


#Function to open up the sub-menu that will allow the user of the script to extrat a choice of performance and device parameters from a network device. 

#The data then needs to be extracted to a MYSQL database within json format.

def ExtractingDataMenu():
	
	selection = ""
	while selection == "":
		os.system('clear') #Clear Screen.
		print("\n\n\n")
		print("\t\t\tThis Is A Sub-menu For Extracting Performance And Device Parameters From Network Devices\n\n\n ")
		print("\tPlease select a choice from the options below.\n\n ")

		print("\t1. Extract the CPU utilisation.")
		print("\t2. Extract the proccessor memory.")
		print("\t3. Extract the I/O memory. ")
		print("\t4. Extract the model of device.")
		print("\t5. Extract the IOS version of device.")
		print("\t6. Exit back to main menu.")
			

		selection = input("\n\t Please select the option you wish to run: ")

		if selection == "1":
			ExtractDataCPU()
		elif selection == "2":
			ExtractDataProcessor()
		elif selection == "3":
			ExtractDataIO()
		elif selection == "4":
			ExtractDataModel()
		elif selection == "5":
			ExtractDataIOS()
		elif selection == "6":
			menu()
		else:
			os.system('clear') #Clear Screen.
			print("\n\n\n\t\t\tYou have entered and incorrect value. ")
			print("\n\t\t\tPress the enter key to return to the main menu. ")
			input ("")


#This is the function to capture network traffic and continuosly output it to a file / files.
#The output will be sotred in pcap format.

def CaptureAndOutputTraffic():
	print("5")



#These functions are the ones to be used within the comparison menu.

#This function compares a devices running configuration with its startup configuration.

def CompareRunningWithStartUpConfig():
	print("Blank")

#This function compares a devices running configuration with a local, offline configuration.

def CompareRunningWithLocalConfig():
	print("Blank")

#This function compares a devices startup configuration with a local, offline configuration.

def CompareStartUpWithLocalConfig():
	print("Blank")


#These functions are the ones used within the extraction menu.

#Function to extract CPU data

def ExtractDataCPU():
	print("Blank")
	


#Function to extract Proccessor Memory data

def ExtractDataProcessor():
	print("Blank")


#Function to extract I/O memory

def ExtractDataIO():
	print("Blank")


#Function to extract Device Model number

def ExtractDataModel():
	print("Blank")


#Function to extra IOS number of device

def ExtractDataIOS():
	print("Blank")


#This function allows the user to leave the script whenever they wish to.

def exit():

	os.system('clear') #Clear Screen.
	sys.exit('\n\n\tThank you for using this script. I hope it met your requirements.\n\n')

#This is the function for the main body of the script.

def main():
	menu()

#This calls the script in order to start it.

main()
__________________________________________________________________________________________________________________________________________

RoutingConfigurationScript.py is the external script i am trying to import as a module into my python menu and activate after the user activates option one on the menu.

It would replace the command 'print("1")' that i currently have there as a placeholder.

__________________________________________________________________________________________________________________________________________
#Import getpass module for use in the script.
#Import the ConnectHnadler from netmkio module to allow the script to SSH.

from getpass import getpass
from netmiko import ConnectHandler

#This ask the user to enter their SSH username to create a variable.
#It then requests the user to enter their SSH password to create a second variable.

username = input('Please enter your SSH username: ')
password = getpass()

#This opens the file 'routercommands_file' for use in the script.

with open('routercommands_file') as f:
	commands_list = f.read().splitlines()

#This opens the file 'routerdevices_file' for use in the script. 

with open('routerdevices_file') as f:
	devices_list = f.read().splitlines()

#This uses the information entered by the user and exterior files to bring forward the correct information when needed to SSH into the device.
#It displays the message 'Connecting to device...' followed by the current IP address of the network device it is accessing. 
#It then uses the variables to connect.

for devices in devices_list:
	print ('Connecting to device" ' + devices)
	ip_address_of_device = devices
	ios_device = {
		'device_type': 'cisco_ios',
		'ip': ip_address_of_device,
		'username': username,
		'password': password

	}

#This finally connects to the device through ssh with ConnectHandler.
#Outputs the commands from the command file.
#Finally, it prints the commands it entered for the user to see.

	net_connect = ConnectHandler(**ios_device)
	output = net_connect.send_config_set(commands_list)
	print (output)
__________________________________________________________________________________________________________________________________________

Thanks for attempting to explain it Larz60, i still don't fully understand but hopefully if someone is able to show me the solution specific to my scripts I'll be able to learn from that.

Thanks.
Reply
#5
Two things:

1. For formatting, please use the python tags so your post is formatted prettier.

2. As I'm reading this, the last bit of code you provided is the one you're importing. It does not have any functions defined in it. So, when you import it, it will simply run its code and be done. To properly import, you need at least one function defined. Any code that is outside of a function or method will simply execute on import.
Reply
#6
sorry, i wasn't too sure how to lay it out properly with the options given.

ah, okay, how would I go about turning the external script into a function so that it can be called at a later date in the main script and doesn't simply run straight away after being imported?
Reply
#7
in the first module replace:
main()
with:
if __name__ == '__main__':
    main()
Buy doing this the module will only load on import, not execute.
You will still, however, be able to run first program stand alone, in which case it will execute.

the check of __name__ will only execute if the module is run from command line, or within IDE, by explicitly running first module,
when imported, however, __name__ will not be equal to __main__, so code will not execute
Reply
#8
By the first module, is it the 'main()' on line 233 of the first script which i am replacing with:

if __name__ == '__main__':
main()

after doing this, how do i actually call the second script into activation in the second on the main script for choice 1?
Reply
#9
yes, be sure to indent main() under the if statement
Reply
#10
After replacing the code with what you suggested I still have the issue of the external script automatically running upon running the main script itself.

i thought the first script was being imported into the second, but I see now that it's the other way around, and I just noticed that the second script was 'C'. That's a different ball game.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  is import cointegration_analysis a recognized module mitcht33 1 384 Nov-06-2023, 09:29 PM
Last Post: deanhystad
  problem in import module from other folder akbarza 5 1,257 Sep-01-2023, 07:48 AM
Last Post: Gribouillis
  can not import anaconda pandas module. PySpark pandas module is imported!! aupres 0 680 Aug-06-2023, 01:09 AM
Last Post: aupres
  import module error tantony 5 3,358 Dec-15-2022, 01:55 PM
Last Post: Lauraburmrs
  Import a module one step back of the path prathampatel9 1 1,033 Sep-21-2022, 01:34 PM
Last Post: snippsat
  Import a module for use in type hint? Milosz 0 1,455 Nov-08-2021, 06:49 PM
Last Post: Milosz
  Can't install nor import delorean module Tek 3 2,741 Oct-27-2021, 03:32 AM
Last Post: Tek
  import module with syntax error Skaperen 7 5,158 Jun-22-2021, 10:38 AM
Last Post: Skaperen
  'urllib3' Module not found when import 'requests' spanz 5 9,954 Jan-06-2021, 05:57 PM
Last Post: snippsat
  Problem with Flask Bcrypt import module marcello86 2 5,595 Aug-31-2020, 08:10 PM
Last Post: marcello86

Forum Jump:

User Panel Messages

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