I am trying to alter some code I have been given for my dissertation. However, any alterations to the modules (print statements, logging, and even trying to deliberately break the code with breaks) do not seem to affect the main program running as if those changes were not there, but changes to the main program does affect the output.
All the changes are saved and I have tried reimporting all the data files I am using and deleting all of the results before rerunning to try and start the program from "fresh". But no luck in fixing the issue.
Is there any fix to this problem? Apologies if it is an easy one, still starting out.
Main Program
eda = EDA()
cdr3_lengths = eda.get_length_of_repertoires(
repertoires=repertoires,
cdr3_col_name="aaSeqCDR3",
freq_col="cloneCount",
groups={
"01.TC8.14": "14days",
"02.TC4.14": "14days",
"03.SC8.14": "14days",
"04.SC4.14": "14days",
"05.TC8.21": "21days",
"06.TC4.21": "21days",
"07.SC8.21": "21days",
"08.SC4.21": "21days",
},
)
Module
class EDA:
# --init method etc --
def get_length_of_repertoires(
self,
repertoires: List,
groups: dict,
cdr3_col_name: str,
freq_col: str,
save_df: bool = False):
print("This isn't working")
cdr3_lengths = {}
self.logger.info("For loop fetching each repertorie.")
for repertoire in repertoires: #Repeat seqs len for count
self.logger.debug(repertoire)
.....
return 'value'
I have added some of the code that I am working with here, I believe it is being executed. I hope this helps a little more.
Related
I started learning Python 2 weeks ago, and now I am trying to code a text adventure game. However, I've run into a problem. So far, I haven't found any solution on Google which can help me.
I decided to store basically all relevant variables in dictionaries - feel free to tell me wether that's even a clever idea or rather stupid of me, I actually do not know this, I just thought it might be a solution that works.
Here's my problem: last thing I decided to insert into the program is a save_game() function. So I defined:
def save_game(data):
import shelve
savegame = shelve.open('./save/savegame')
savegame['data'] = data
savegame.close()
And of course, if I then call
save_game(save_game_data)
with save_game_data being the dictionary where I've put all the other dictionaries so I can handle saving with a single function call (I thought that might be better?), it actually works.
But of course a save_game() only makes sense if you can also reload the data into the program.
So I defined:
def load_game(data):
import shelve, time
savegame = shelve.open('./save/savegame')
data = savegame['data']
data = dict(data) # This was inserted because I hoped it would solve my problem, but it doesn't
savegame.close()
But the result of
load_game(save_game_data)
Unfortunately is no updated dictionary save_game_data with all the keys and values, and I just can't get my head around how to get all the stored data back into values in the dictionaries. Maybe I'm on a totally wrong way all together, maybe I just don't know enough about Python yet to even know where I'm erring.
The save_game() and load_game() functions are in a different file from the main file, and are correctly imported if that is relevant.
It looks like you're trying to pass save_game_data to load_game() as if to mean "load data and put it into save_game_data" but this isn't what load_game() is doing. By doing this:
def load_game(data):
import shelve, time
savegame = shelve.open('./save/savegame')
data = (savegame['data'])
You're replacing what data refers to, so save_game_data doesn't get changed.
Instead, you can drop the argument to load_game() and add:
return data
at the end of the function, and call it like this:
save_game_data = load_game()
For some days I've been breaking my head over some issues I'm having with a Win32Com Excel object in python.
What I'm trying to do is very simple; get the sheet names from a workbook and write a value to the bottom of a column. The workbook is often opened by the users and needs to remain accessible/editable, hence I decided to use Win32Com. Any other suggestions to achieve the same are very welcome as well.
The base-code is quite straightforward:
class excelCOM():
def __init__(self, file):
self.xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
self.wb = self.xl.Workbooks(os.path.basename(file))
def getSheets(self):
return [s.Name for s in self.wb.Sheets]
def dataToCell(self, sheet, column, string):
sht = self.wb.Sheets(sheet)
maxLastCell = sht.Range('{}{}'.format(column, 1048576))
lastCell = maxLastCell.End(win32com.client.constants.xlUp)
lastCell.Offset(2, 1).Value = string
Issues occur when integrated with the rest of the software. I've gone through lots of documentation and trying different things but I've been unable to get a reliable result. I'll try my best to summarize what I've tried and what the observations were.
When I create a single instance of this class and run the methods, everything works as expected.
if __name__ == '__main__':
xlWb = excelCOM(r"TestBook.xlsx")
print(xlWb.getSheets())
xlWb.dataToCell("Sheet1", 'B', 'All Good')
The information to write to the excel file comes from a logfile that is being written to by another (external) program. My software monitors the file and writes to excel whenever there is a new line added. All of this is handled by the 'processor'. The formatting for the text that's written to excel is user defined. Those formatting settings (and others) are imported to the processor from a pickled (settings) object (allowing the user to save settings (using a GUI) and run the processor without needing the GUI). As code (extremely simplified, just to get the idea across):
class processor():
def __init__(self, settings_object):
self.com_object = excelCOM(settings_object.excel_filepath)
self.file_monitor(settings_object.input_filepath)
self.file_monitor.start()
def dispatch():
# called whenever file_monitor registers a change to the file at input_filepath
last_line = self.get_last_line(input_filepath)
sheet, column, formatted_text = self.process(last_line)
self.com_object.dataToCell(sheet, column, formatted_text)
Now, when text is supposed to be written to the excel file by the processor, I get Exception in thread Thread-1: pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) at sht = self.wb.Sheets(sheet)
When I call CoInitialize() before sht = self.wb.Sheets(sheet) I get Exception in thread Thread-1: pywintypes.com_error: (-2147417842, 'The application called an interface that was marshalled for a different thread.', None, None). Calling CoInitialize() anywhere else in the code doesn't seem to do anything.
Adding the same code as in init solves the issue from point 3, but this seems very wrong to me. Mainly because I don't exactly know why it fixes the issue and what's going on in the background with com objects in windows.
def dataToCell(self, sheet, column, string):
pythoncom.CoInitialize() # point 3.
self.xl = win32com.client.gencache.EnsureDispatch('Excel.Application') # point 4.
self.wb = self.xl.Workbooks(os.path.basename(self.file)) # point 4.
sht = self.wb.Sheets(sheet)
maxLastCell = sht.Range('{}{}'.format(column, 1048576))
lastCell = maxLastCell.End(win32com.client.constants.xlUp)
lastCell.Offset(2, 1).Value = string
Now switching to the GUI. As mentioned earlier, the settings file for the processor is created with help from a GUI. It basically gives the functionally to build the settings_object. In the GUI I also have a 'run' button which directly calls processor(settings_object) in a seperate Thread. When I do this, I don't even need to add the additional lines as described in point 3 and 4. It runs perfectly with just the base-code.
I've gone through dozens of pages of documentation, StackOverflow topics, tutorials, blogs hidden in the dark corners of the web, Python Programming on Win32 but I simply can't wrap my head around what's going on. I consider myself a half-decent programmer for 'get the job done' applications but I don't have any education in computer science (or even programming in general), which is what I suspect I'm lacking at the moment.
I'm hoping someone can point me in the right direction for understanding this behavior and maybe give some advice on the proper way of implementing this functionality for my scenario.
Please let me know if you require any more information.
Best regards and many thanks in advance,
RiVer
i have written lines of code that run normally in jupyter notebook (here is the code below):
umd_departments = requests.get("https://api.umd.io/v0/courses/departments")
umd_departments_list = umd_departments.json()
umd_departments_list2 = json.dumps(umd_departments_list, indent=1)
department_storage = [department['dept_id'] for department in umd_departments_list]
print(department_storage)
the code above usually gives me the output i want and prints it out immediately. the issue i run into is when i try and put the code above into a function of its own it doesn't work
def get_UMD_departments():
umd_departments = requests.get("https://api.umd.io/v0/courses/departments")
umd_departments_list = umd_departments.json()
umd_departments_list2 = json.dumps(umd_departments_list, indent=1)
department_storage = [department['dept_id'] for department in umd_departments_list]
print(department_storage)
the problem i face with this version of code is that it never prints out anything as oppose to the other code i showed. with this code, i also don't get an error when i run it since the * symbol doesn't show up and i don't get an error message. so i'm not sure what the problem is. it usually just shows how many times i ran the cell. i was wondering if anyone knew a way to make the function version of my code to work, greatly appreciated.
I am working on a mini GUI project , I am currently struggling to figure out how to get selected value from the list and then return that value to the main function so that I can use that value in somewhere else . Can someone help me please !!!!
####
self.device_list_store = gtk.ListStore(str,str,str,str,str)
for device in self.get_dev_list():
self.device_list_store.append(list(device))
device_list_treeview = gtk.TreeView(self.device_list_store)
selected_row = device_list_treeview.get_selection()
selected_row.connect("changed",self.item_selected)
####
def item_selected(self,selection):
model,row = selection.get_selected()
if row is not None:
selected_device = model[row][0]
at the moment ,the item_selected function is not returning anything , I want to return selected_device back to the main function so I can use it in other functions as well .
EDIT: I've edited code above to remove formatting errors #jcoppens
As you can see in the documentation, the item_selected function is called with one parameter, tree_selection. But if you define the function inside a class, it requires the self parameter too, which is normally added automatically. In your (confusing) example, there is no class defined, so I suspect the problem is your program which is incomplete.
Also, I suspect you don't want device_list_treeview = gtk.T... in the for loop:
for device in self.get_dev_list():
self.device_list_store.append(list(device))
device_list_treeview = gtk.TreeView(self.device_list_store)
And I suspect you want selected_device = mod... indented below the if:
if row is not None:
selected_device = model[row][0]
Please convert your example in a complete program, and formatted correctly.
BTW: item_selected is not a good name for the signal handler. It is also called if the item is unselected (which is why the signal is called 'changed')!
And important: Even though you should first read the basic Python tutorials and Gtk tutorials, you should then consider using lazka's excellent reference for all the Python APIs. There's a link on the page to download it completely and have it at hand in your computer.
So, I have a function which basically does this:
import os
import json
import requests
from openpyxl import load_workbook
def function(data):
statuslist = []
for i in range(len(data[0])):
result = performOperation(data[0][i])
if result in satisfying_results:
print("its okay")
statuslist.append("Pass")
else:
print("absolutely not okay")
statuslist.append("Fail" + result)
return statuslist
Then, I invoke the function like this (I've added error handling to check what will happen after stumbling upon the reason for me asking this question), and was actually amazed by the results, as the function returns None, and then executes:
statuslist = function(data)
print(statuslist)
try:
for i in range(len(statuslist)):
anotherFunction(i)
print("Confirmation that it is working")
except TypeError:
print("This is utterly nonsense I think")
The output of the program is then as follows:
None
This is utterly nonsense I think
its okay
its okay
its okay
absolutely not okay
its okay
There is only single return statement at the end of the function, the function is not recursive, its pretty straightforward and top-down(but parses a lot of data in the meantime).
From the output log, it appears that the function first returns None, and then is properly executed. I am puzzled, and I were unable to find any similar problems over the internet (maybe I phrase the question incorrectly).
Even if there were some inconsistency in the code, I'd still expect it to return [] instead.
After changing the initial list to statuslist = ["WTF"], the return is [].
To rule out the fact that I have modified the list in some other functions performed in the function(data), I have changed the name of the initial list several times - the results are consistently beyond my comprehension
I will be very grateful on tips in debugging the issue. Why does the function return the value first, and is executed after?
While being unable to write the code which would at the same time present what happened in my code in full spectrum, be readable, and wouldn't interfere with no security policies of the company, I have re-wrote it in a simpler form (the original code has been written while I had 3 months of programming experience), and the issue does not reproduce anymore. I guess there had be some level of nesting of functions that I have misinterpreted, and this re-written code, doing pretty much the same, correctly returns me the expected list.
Thank you everyone for your time and suggestions.
So, the answer appears to be: You do not understand your own code, make it simpler.