# randomize.py
import os
import sys
import re
import shuti1
import json
import cProfile
import random
li = ["dog dot", "do don't", "dumb-dumb", "no match"]
for element in li:
m = re.match("(d\w+)\W(d\w+)", element)
if m:
print(m.groups())
for _, __ in enumerate(sys.path):
shuti1.initialize('Hello', '!', 'HackerEarth')
print __
while True:
li_random = random.choice(li)
print li_random
if li[0] in li_random:
break
# shuti1.py
import sys
import randomize
import collections
import math
from collections import Counter
class HackerEarth(object):
def __init__(self, name, role, hobby):
self.name = name
self.role = role
self.hobby = hobby
def print_details(self):
print "Name:", self.name
print "Role:", self.role
print "Hobby:", self.hobb
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
def initialize(greet, character, company):
print greet, character, company
when i run the program i got the error like:
Traceback (most recent call last):
File "C:/Users/SAGAR/Desktop/randomize.py", line 5, in <module>
import shuti1
File "C:\Python34\shuti1.py", line 3, in <module>
import randomize
File "C:/Users/SAGAR/Desktop\randomize.py", line 18, in <module>
shuti1.initialize('Hello', '!', 'HackerEarth')
AttributeError: 'module' object has no attribute 'initialize'
I'm gonna take a guess that initialize is part of the HackerEarth class as you didn't indent much to be sure. If that's the case, initialize is not part of the module, it is part of the class, so you would need a HackerEarth object in order to call it.
If that isn't the case, it could be the cyclic imports that Peter Wood mentioned (sorry, don't know how to tag!). What that means is that you are importing shuti1.py into randomize.py and randomize.py into shuti1.py. This can be confirmed looking at the error message:
File "C:/Users/SAGAR/Desktop/randomize.py", line 5, in
import shuti1
File "C:\Python34\shuti1.py", line 3, in
import randomize
Lastly, it could be caused by an IDE if you are using one. Pycharm requires all imported files to be in the project or part of your python directory. Check for something like that if you can't fix it with the other 2 things.
Hope it helps
Related
I have multiple py files with unit tests specified for specific module.
I want to import these unittests to seperate py file and run them from there, but I have trouble getting it working.
example of one of the unittest:
from webdriver_manager.chrome import ChromeDriverManager
from to_import import acceptConsent, URL_poznavacky, URL_poznavacky_vikendy, URL_poznavacky_rodiny, URL_pobocky
import time
from selenium import webdriver
import unittest
class TestPobocky_D(unittest.TestCase):
def setup_method(self, method):
self.driver = webdriver.Chrome(ChromeDriverManager().install())
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_pobocky_D(self):
self.driver.get(URL_pobocky)
acceptConsent(self.driver)
self.driver.maximize_window()
time.sleep(2)
mapa = self.driver.find_element_by_xpath("//*[#class='leaflet-pane leaflet-tile-pane']") ## jen jeden element, no need to call find_elementS
mapaDisplayed = mapa.is_displayed()
assert mapaDisplayed == True
mapaKolecka = self.driver.find_elements_by_xpath("//*[#class='leaflet-marker-icon marker-cluster marker-cluster-medium leaflet-zoom-animated leaflet-interactive']")
y=0
for _ in mapaKolecka:
mapaKoleckaDisplayed = mapaKolecka[y].is_displayed()
y=y+1
print("mapa kolecka")
assert mapaKoleckaDisplayed == True
pobockaBoxiky = self.driver.find_elements_by_xpath("//*[#class='f_branch-header f_anchor']")
x=0
for _ in pobockaBoxiky:
pobockaBoxikyDisplay = pobockaBoxiky[x].is_displayed()
print("boxiky")
assert pobockaBoxikyDisplay == True
x=x+1
basicInfo = self.driver.find_elements_by_xpath("//*[#class='f_branch-basicInfo']")
a=0
for _ in basicInfo:
basicInfoDisplay = basicInfo[a].is_displayed()
print("basic info ")
assert basicInfoDisplay == True
a=a+1
I want to import the whole class TestPobocky_D to new file and run it in seperate py file. I tried following:
import unittest
from pobocky import TestPobocky_D
TestPobocky_D(unittest.TestCase)
that just gives me this error
"Traceback (most recent call last):
File "C:/Users/KDK/Desktop/Automation_Local_Deploy_PyCharm/starter_local.py", line 4, in <module>
TestPobocky_D(unittest.TestCase)
File "C:\Users\KDK\anaconda3\lib\unittest\case.py", line 433, in __init__
testMethod = getattr(self, methodName)
TypeError: getattr(): attribute name must be string"
Anyone who can help me with this please ? Or point me to the right direction how to go about this.
Thanks in advance for every response
Can you please try as below?
starttest.py
import unittest
from pobocky import TestPobocky_D
if __name__ == '__main__':
unittest.main(argv=[''],verbosity=2, exit=False)
Run the command "python -m unittest starttest.py"
I am running the following script:
# STEP 1: import packages, declare tindexes
import pandas as pd
import yfinance as yf
import datetime as dt
bnpl_tindex = ["APT.AX","Z1P.AX","LFS.AX","SZL.AX","HUM.AX","SPT.AX","OPY.AX","IOU.AX","LBY.AX","DOU.AX"]
target_dates = pd.date_range(start=dt.date.today() - dt.timedelta(days=365), end=dt.date.today(), freq="M").strftime('%Y-%m-%d')
target_dates = target_dates.append(pd.Index([dt.date.today().strftime('%Y-%m-%d')]))
target_dates.sort_values()
#STEP 2: source functions
from collect_index_data import collect_index_data
#DELETE LATER... TESTING!
collect_index_data(bnpl_tindex, target_dates)
#
collect_index_data is as follows:
def collect_index_data(ticker_list,date_list):
if (bool(ticker_list) and all(isinstance(elem, str) for elem in ticker_list) )==False:
sys.exit('Input should be a list or a single string.')
else:
print("Components of Index: ")
#initialise dictionary
d = {}
#loop through ticker list
for x in ticker_list:
d["DF.{0}".format(x)] = yf.Ticker(x)
#testing
print(x)
#testing
print(d)
and I get the following error message
Components of Index:
Traceback (most recent call last):
File "C:\Users\thoma\Desktop\Files\Programming\Python\run_tindex_data.py", line 27, in <module>
collect_index_data(bnpl_tindex, target_dates)
File "C:\Users\thoma\Desktop\Files\Programming\Python\collect_index_data.py", line 12, in collect_index_data
d["DF.{0}".format(x)] = yf.Ticker("MSFT")
NameError: name 'yf' is not defined
My question is why is yfinance package not being recognised in my function?
I could import it inside the function, but I plan to run the function multiple times in a script - so this would be computationally wasteful.
thanks!
Im brand new to python and coding, im trying to get below working.
this is test code and if I can get this working I should be able to build on it.
Like I said im new to this so sorry if its a silly mistake.
# coding=utf-8
import ops # Import the OPS module.
import sys # Import the sys module.
import re
# Subscription processing function
def ops_condition (o):
enter code herestatus, err_str = o.timer.relative("tag",10)
return status
def ops_execute (o):
handle, err_desp = o.cli.open()
print("OPS opens the process of command:",err_desp)
result, n11, n21 = o.cli.execute(handle,"return")
result, n11, n21 = o.cli.execute(handle,"display interface brief | include Ethernet0/0/1")
match = re.search(r"Ethernet0/0/1\s*(\S+)\s*", result)
if not match:
print("Could not determine the state.")
return 0
physical_state = match[1] # Gets the first group from the match.
print (physical_state)
if physical_state == "down":
print("down")
result = o.cli.close(handle)
else :
print("up")
return 0
Error
<setup>('OPS opens the process of command:', 'success')
Oct 17 2018 11:53:39+00:00 setup %%01OPSA/3/OPS_RESULT_EXCEPTION(l)[4]:Script is test.py, current event is tag, instance is 1515334652, exception reason is Trac eback (most recent call last):
File ".lib/frame.py", line 114, in <module>
ret = m.ops_execute(o)
File "flash:$_user/test.py", line 22, in ops_execute
physical_state = match[1] # Gets the first group from the match.
TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'
The __getitem__ method for the regex match objects was only added since Python 3.6. If you're using an earlier version, you can use the group method instead.
Change:
physical_state = match[1]
to:
physical_state = match.group(1)
Please refer to the documentation for details.
I have a NameError that I cannot seem to be able to find the reason for. The error trace ends like this.
Traceback (most recent call last):
File ".../new_main.py", line 61, in <module>
if __name__ == "__main__": main()
File ".../new_main.py", line 39, in main
mp = build()
File ".../common.py", line 54, in build
m = r.build_from_config(map_config, character_config)
File ".../config_reader.py", line 148, in build_from_config
item["squares"]
File ".../new_map.py", line 49, in build_map
self.view = MapView(self)
File ".../new_map.py", line 135, in __init__
self.screen = reset_screen()
NameError: name 'reset_screen' is not defined
The class MapView() is in the file new_map.py and that file has this line in the imports:
from common import *
And the file common.py has the following function in it.
def reset_screen():
# check if display has been initialized
if not pygame.display.get_init():
pygame.init()
# set screen
#flags = pygame.FULLSCREEN | pygame.DOUBLEBUF
screen = pygame.display.set_mode( options.window_size )
# fill with black
screen.fill(BLACK)
return screen
What am I missing?
E: here are my imports for each file.
new_main.py:
from common import *
from new_map import Map, MapView
import pygame, sys
common.py:
import pygame
import options
from config_reader import ConfigReader
from constants import *
from coordinates import Coordinates
config_reader.py:
from action import Action
from new_map import Map
from object_type import ObjectType
from squaretype import SquareType
from new_character import Character
from coordinates import Coordinates
import direction
new_map.py:
from square import Square
from common import *
from constants import *
from coordinates import Coordinates
from map_object import MapObject
from object_type import ObjectType
from new_character import Character
from turn import TurnController
import pygame, os
Looking at your trace i can also just figure that in your common.py your are including new_map.py which causes the import in new_map to fail. If i do that to my test files, i get the same error:
my main - which imports both but still won't cause circular reference:
if __name__ == "__main__":
from common import * # <-- this is ok
from new_map import * # <-- this is no problem
do_something()
test()
my commons:
from new_map import * # <--- this will cause the problem
def reset_screen():
return 1
def do_something():
return test()
my new_map:
from common import * # <--- this will fail then
def test():
return reset_screen()
So you will have to split you common.py to the parts using new_map and the other that don't, and in new_map then import the version that holds the functions without new_map inclusion.
common_map.py
from new_map import *
def do_something()
return test()
common_nomap.py
def reset_screen()
return 1
new_map.py:
from common_nomap import *
def test()
return reset_screen()
main.py
if __name__ == "__main__":
from common_map import * # <-- this is ok
from new_map import * # <-- this is no problem
do_something()
test()
2 possible scenarios I can think of:
Circular deps: it looks like common.py activates the function in new_map.py (via config_reader.py), which might cause new_map.py not to import common.py
Is there a common package you might be importing instead of common.py?
from PIL import Image
import input_class
import input_function
import input_crop_values
import input_translate
class ImageChanger():
def __init__ ():
image_filename = input_class.input_file_name()
self.my_image = Image.open(image_filename)
chosen_Function = input_function.input_vaild_function()
if chosen_Function == "Crop" or chosen_Function == "crop":
crop_values = input_crop_values.input_crop_data()
my_image.crop(crop_values)
elif chosen_Function == "Translate" or chosen_function == "translate":
translate_values = input_translate.input_translate_data()
my_image.crop(translate_values)
else:
print("unexpected error while running code")
def printState():
print( "Your image file name is %s" % self.my_filename );
return (self.my_filename);
def translate(self,x_cord,y_cord):
return (self.my_image.offset(x_cord,y_cord));
def crop(self, box):
return (self.my_image.crop(box))
sorry for odd formatting,
Error:
Traceback (most recent call last):
File "C:\Users\Alexander\Desktop\Final_Udacity_project\dragon_picture_test.py", line 1, in <module>
import picture_changer
File "C:\Users\Alexander\Desktop\Final_Udacity_project\picture_changer.py", line 3, in <module>
import input_function
File "C:\Users\Alexander\Desktop\Final_Udacity_project\input_function.py", line 14
else
^
SyntaxError: invalid syntax
I have some other functions, not listed that use the input command sort of like a user interface, then it returns it to the larger class.
The places that the values are returned and what is return is:
line 8*: image_filename = input_class.input_file_name() # you would give a name of a picture here,
line 10*: chosen_function = input_function.input_vaild_function() # you Would give it either crop or translate can be sentence case or lowercase
line 11*: crop_values = input_crop_values.input_crop_data() # you would give it data in brackets like [1,2,3,4] and it would crop it.
line 15*: translate_values = input_translate.input_translate_data() # you would give it information in ( ), like (1,2,3,4) and it would translate it.
The code is acting really weird with the Boolean and the error message isn't helping me that much.
else, like other statements that come before a block, requires a colon.
else: