Bug import main with arguments in Python - python

In a script I'm trying to import the main module from another script with an argument.
I get the error message "NameError: global name 'model' is not defined".
If someone sees the mistake, I'd be grateful !
My code :
script1
#!/usr/bin/python
import sys
import getopt
import pdb
import shelve
class Car:
""" class representing a car object """
def __init__(self, model):
self.model = model
class Porsche(Car):
""" class representing a Porsche """
def __init__(self, model):
Car.__init__(self, model)
print "I have a Porsche but no driving licence : too bad !"
# Main
def main(argv):
settings = shelve.open('mySettings')
global model
try:
opts, args = getopt.getopt(argv, "m:", ["model="])
except getopt.GetoptError, err:
print " wrong argument, exiting "
sys.exit()
for opt, arg in opts:
if opt in ("-m", "--model"):
model = arg
def choose_car(model):
""" Creates the car"""
my_Porsche = Porsche(model)
choose_car(model)
if __name__ == "__main__":
main(sys.argv[1:])
script2
#!/usr/bin/python
import os
import sample
import sys
def main(argv):
script1.main("-m Carrera")
# Main program
if __name__ == '__main__':
main(sys.argv[1:])
rgds,

argv is a list. Therefore you should call script1.main as
script1.main(['-m', 'Carrera'])
or, equivalently,
script1.main('-m Carrera'.split())

Related

How to trigger an event from caller file where trigger class is in another file?

I have a simple class that monitors a folder path using the "WatchDong" library. The watchdog monitoring class is in the file_monitor.py file.
import watchdog.events
import watchdog.observers
class Handler(watchdog.events.PatternMatchingEventHandler):
def __init__(self):
# Set the patterns for PatternMatchingEventHandler
watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.tif','*.jpg'],
ignore_directories=True, case_sensitive=False)
def on_created(self, event):
print("File added - % s." % event.src_path)
#updateNewImageFiles(event.src_path)
def main():
if __name__ == "__main__":
main()
My main file "Monitor_main.py" uses the class in the previous file and the code is as follows :
import file_monitor
def file_addon_event():
print("File created : ")
def main():
FM = file_monitor.Handler(OnCreate = file_addon_event)
if __name__ == "__main__":
main()
I want to trigger "file_addon_event()" on an event of a file created in folder in Monitor_main.py. How can I trigger 'file_addon_event()' here ?
This is the example I wanted to look like :
FM = file_monitor.Handler(OnCreate = file_addon_event)

The same code is running on the jupyter note book but not on the Spyder. Can anyone please tell me that why this is giving error?

import math
import unittest
class Calculator:
def __init__(self):
pass
def is_sum(a,b):
return a+b
is_sum(10,5) #Here is the issue
import unittest
class CalculatorTest(unittest.TestCase):
def test_add(self):
self.assertTrue(self.Calculator.is_sum.is_number(a))
self.assertTrue(self.Calculator.is_sum.is_number(b))
if __name__ == "__main__":
unittest.main()

Using Python Click within a class

I've got an old flashcards app that I made that I've repurposed for some aws cert study. I wrote this years ago and overhauled that code, and one of those changes involved using click over argparse, but I'm having some issues using click. My code is below (minus a couple of extra functions):
The idea is that load_deck() needs to read the file argument. The way that I was trying to do it is pass load_deck() the file argument through main()
Finally, running this code states that within the Flashcards().main() call, main() is missing a positional argument self. I think this is a problem with the way I'm using click.
import os
import random
import sys
import click
import keyboard
import ruamel.yaml
class Flashcards:
"""
pass
"""
def __init__(self):
self.deck = ruamel.yaml.YAML()
self.card = ['key', 'value']
def load_deck(self, file):
"""
pass
"""
with open(file, mode='r') as deck:
self.deck = self.deck.load(deck)
#click.command()
#click.option('-f', '--file', default='aws.yaml', help='specifies yaml file to use')
#click.option('-r', '--reverse', default=False, help='displays values prompting user to guess keys')
def main(self, file, reverse):
"""
pass
"""
self.load_deck(file)
if reverse is True:
self.deck = [
[card[1], card[0]
] for card in self.deck]
os.system('clear')
print('Press [SPACEBAR] to advance. Exit at anytime with [CTRL] + [C]\n'
'There are {} cards in your deck.\n'.format(len(self.deck)))
try:
while True:
self.read_card()
self.flip_card()
except KeyboardInterrupt:
# removes '^C' from terminal output
os.system('clear')
sys.exit(0)
if __name__ == "__main__":
Flashcards().main()
The program reads a yaml file in the following format (it was previously a spanish flashcard app):
bajar: to descend
borrar: to erase
contestar: to answer
Click isn't naturally designed to work this way, see for example this issue which also includes some workarounds by folks in the comments if you want to go that route.
In your case, you could just yoink main out of the class and have it instantiate Flashcards for you:
#click.etc.
def main(file, reverse):
f = Flashcards()
f.load_deck(file)
# And so on, using 'f' instead of 'self'
I found this workaround:
import click
class Stub:
pass
viking = click.make_pass_decorator(Stub,ensure=True)
#click.group()
#viking
#click.pass_context
def cli(ctx,_):
ctx.obj = Viking()
class Viking(Stub):
def __init__(self):
self.name = "Thor"
#cli.command()
#viking
def plunder(self):
print(f"{self.name} attacks")
#cli.command()
#viking
def sail(self):
print("whoosh")
cli()

Python access parseargs from other class

there is an executable main.py file who takes as argument a savefile, how can I check in an other class if the savefile was given over?
code main.py:
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="test")
parser.add_argument('--savefile', help="A savefile")
args = parser.parse_args()
if(args.savefile):
from A import A
a = A()
a.run() //executes the run function in A
class A.py
class A(){
def run():
import main
if(main.args.savefile):
//do sth
}
However I always seem to get the AttributeError: module 'main' has no attribute 'args'
Appreciate any help, ty.
You could use something like the following pattern to avoid dangerous imports.
The main change is in the class, where we declare the __init__ function to accept the parameter we will give in the main file.
#file A.py
class A():
def __init__(self, savefile=None):
self.savefile = savefile
def run(self):
if self.savefile:
# do sth
print(self.savefile)
# main.py
import argparse
from A import A
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="test")
parser.add_argument('--savefile', help="A savefile")
args = parser.parse_args()
if args.savefile:
a = A(args.savefile)
a.run()

How to executing the method from the test __main__ in Python unit-test?

I am trying to set the precondition for the test first prior to test other test cases. But as you can see in my code the precondition print command is not fired! Can you explain the cause and solution how to fire the code with in that method i.e. SetPreConditionFirewall() in my case.
Here is my code:
#! /usr/bin/env python
__author__ = 'Milson Munakami'
__revision__ = '0.0.2'
import json
import urllib
#import time
#from util import *
import httplib
#import sys
#from scapy.all import *
import unittest
import os, sys, socket, struct, select, time
from threading import Thread
import logging
import traceback
class testFirewallS1( unittest.TestCase ):
def setUp(self):
self.controllerIp="127.0.0.1"
def tearDown(self):
if self.failed:
return
duration = time.time() - self.startTime_
self.cleanup(True)
if self.reportStatus_:
self.log.info("=== Test %s completed normally (%d sec)", self.name_, duration)
def cleanup(self, success):
sys.excepthook = sys.__excepthook__
try:
return
except NameError:
self.log.error("Exception hit during cleanup, bypassing:\n%s\n\n" % traceback.format_exc())
pass
else:
fail("Expected a NameError")
def SetPreConditionFirewall(self):
command = "http://%s:8080/wm/firewall/module/enable/json" % self.controllerIp
urllib.urlopen(command).read()
print self.controllerIp
print "Test Pre-condition setting here"
#Precondition Test
def testPreConditionFirewall(self):
print "Test pass"
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(testFirewallS1))
return suite
if __name__ == '__main__':
suiteFew = unittest.TestSuite()
testFirewallS1("SetPreConditionFirewall")
suiteFew.addTest(testFirewallS1("testPreConditionFirewall"))
#Testing the Test Cases Begins Here
unittest.TextTestRunner(verbosity=2).run(suiteFew)

Categories

Resources