What is the SyntaxError in the a "def" line in a python script? - python-3.x

I am trying to run the follow python script:
#!/usr/bin/env python
#Author Jared Adolf-Bryfogle
#Python Imports
import os
import sys
from pathlib import Path
from typing import Union
#Append Python Path
p = os.path.split(os.path.abspath(__file__))[0]+"/src"
sys.path.append(p) #Allows all modules to use all other modules, without needing to update pythonpath
#Project Imports
from pic2.modules.chains.ProposedIgChain import ProposedIgChain
from pic2.modules.chains.IgChainSet import IgChainSet
from pic2.modules.chains.IgChainFactory import IgChainFactory
from pic2.modules.chains.AbChainFactory import AbChainFactory
from pic2.tools.fasta import *
class IgClassifyFASTA:
"""
Identify CDRs from a Fasta File
"""
def __init__(self, fasta_path: Union[Path, str]):
self.fasta_path = str(fasta_path)
self.outdir = os.getcwd()
self.outname = "classified"
self.fasta_paths = split_fasta_from_fasta(os.path.abspath(self.fasta_path), "user_fasta_split_"+self.outname, self.outdir)
def __exit__(self):
for path in self.fasta_paths:
if os.path.exists(path):
os.remove(path)
def set_output_path(self, outdir: Union[Path, str]):
self.outdir = str(outdir)
def set_output_name(self, outname: Union[Path, str]):
self.outname = str(outname)
My python version is 3.8, and the pic2 is a conda env. I get the the following error:
File "IgClassifyFASTA.py", line 29
def __init__(self, fasta_path:Union[Path, str]):
SyntaxError: invalid syntax
I cannot figure out what's wrong with this line. Could you kindly give me some hint what's the wrong lying in? I will appreciate any help.
Best regards!

Related

how to pytest a pyqt application that uses argparse for input parameters

I have a PyQt application that uses argparse to pass some argument.
I managed to write a simple test to see if the app starts
but I cannot set/mock the argparse arguments
I know it because inside the code I have some try/except like this
try:
if args.erase_data:
pass
except NameError:
logger.error("Error in parsing erase_data input argument \n")
that during the tests fail, while they do not fail if I run the app.
I tried this to mock args
import os
import pathlib
# import pdb
import sys
from unittest import mock
import pytest
from PyQt5 import QtTest
from PyQt5.QtWidgets import *
from pytestqt.plugin import QtBot
sys.path.append(os.getcwd())
src_dir = pathlib.Path(__file__).parents[1].absolute()
print(src_dir)
sys.path.append(src_dir.as_posix())
GUI = __import__("GUI")
#pytest.fixture(scope="module")
def qtbot_session(qapp, request):
result = QtBot(qapp)
with capture_exceptions() as e:
print(getattr(e, "message", repr(e)))
yield result
print(" TEARDOWN qtbot")
#pytest.fixture(scope="module")
def Viewer(request):
with mock.patch.object(sys, "argv", ["",'-d','2']):
print("mocking sys argv")
print(sys.argv)
# pdb.set_trace()
app, app_window = GUI.main()
qtbotbis = QtBot(app)
QtTest.QTest.qWait(0.5 * 1000)
assert app_window.isVisible()
return app, app_window, qtbotbis
but args is still not set.
any idea how to solve it?

Creating a class with Selenium in Python

I am just trying to create a class for bot testing with Selenium. Here's the layout of my project:
Project/
booking/
__init__.py
booking.py
constants.py
run.py
Run.py is where I am trying to run the code, outside of the booking folder, but inside of the Project folder, run.py:
from booking.booking import Booking
inst = Booking()
inst.land_first_page()
In my booking.py code:
from selenium import webdriver
import os
import booking.constants as const
class Booking(webdriver.Chrome):
def __init__(self, driver_path=r"C:/Selenium Drivers/chromedriver.exe"):
self.driver_path = driver_path
os.environ['PATH'] += self.driver_path
super(Booking, self).__init__()
def land_first_page(self):
self.get(const.BASE_URL)
I keep getting the error 'chromedriver' executable needs to be in PATH, but I thought
this line would take care of that:
os.environ['PATH'] += self.driver_path
How can I fix this?
Instead of
os.environ['PATH'] += self.driver_path
try using
os.environ["PATH"] += os.pathsep + self.driver_path
or
os.environ["PATH"] += os.pathsep + driver_path

How to check if module import fails and output relvant error?

New to python
I want to do this:
def imp_modules(module):
try:
import module
except moduleName as failedModule:
print('Module ' + failedModule + ' failed to import ...')
sys.exit(1)
That is an example of what I want to achieve. I want all the modules I am importing to go through that function. I don't want to have any import module_name outside that function.
Can this be achieved with a solution that is windows/linux compatible?
You have to except a specific error, ModuleNotFoundError. Also, to import module from it's name, use importlib:
import importlib
def imp_modules(module_name):
try:
globals()[module_name] = importlib.import_module(module_name)
except ModuleNotFoundError as err_message:
failedModule = err_message.msg.split("'")[1]
print(f"Module '{failedModule}' failed to import ...")
sys.exit(1)
#USAGE:
imp_modules("module_name")
You could also have the function iterate over all the modules to import:
import importlib
def imp_modules(*module_names):
for module_name in module_names:
try:
globals()[module_name] = importlib.import_module(module_name)
except ModuleNotFoundError as err_message:
failedModule = err_message.msg.split("'")[1]
print(f"Module '{failedModule}' failed to import ...")
sys.exit(1)
#USAGE:
imp_modules("module_one_name","module_two_name", ...)

Python 3.6 - AttributeError: module 'tkinter' has no attribute 'filedialog'

My function was working perfectly fine few minutes ago. Did not modify the code, just installed PyAudio. I get the error as per subject. It doesn't matter if run it from command line or IDE, same error. Any ideas?
def DataFinder():
#imports and initialize
import pandas as pd
import tkinter as tk
finder = tk.Tk()
finder.withdraw()
__dataFlag = False
#ask user to select a file
__path = tk.filedialog.askopenfilename()
#check the extension to handle reader
#for csv files
if __path.endswith('.csv')==True:
df = pd.read_csv(__path,header=0)
return df
__dataFlag = True
#and for excel files
elif __path.endswith('.xls')==True:
df = pd.read_excel(__path,header=0)
return df
__dataFlag = True
#if a file is not a supported type display message and quit
else:
__dataFlag = False
#check if there is a data to be returned
if __dataFlag==True:
return df
else:
print('The file format is not supported in this version.')
Explicitly import of filedialog can solve the problem.
So, you just need to add this line to your codes:
import tkinter.filedialog
You can find more information at Why tkinter module raises attribute error when run via command line but not when run via IDLE?
the following code didn't work for me:
import tkinter as tk
import tkinter.filedialog
But the following did work:
import tkinter
import tkinter.filedialog
and also this:
import tkinter.filedialog
import tkinter as tk
Hope this helps
Note
As mentioned by Vaidøtas I., you can't import filedialog from tkinter. Because you did not import the original tkinter but an aliased version tk.

Invalid syntax when trying to add patch_http_response_read patch

Hello i'm trying to patch my python code with http://bobrochel.blogspot.com/2010/11/bad-servers-chunked-encoding-and.html but when adding this snippet anywhere in the code I always get invalid syntax. What am I doing wrong?
The start of my code looks like this:
import logging
import argparse
import sys
from arbitrer import Arbitrer
def patch_http_response_read(func):
def inner(*args):
try:
return func(*args)
except httplib.IncompleteRead, e:
return e.partial
return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
class ArbitrerCLI:
def __init__(self):
except doesn't work that way anymore.
except httplib.IncompleteRead as e:
Indent correctly.
The try statement changed in Python 3.x.
import httplib
import logging
import argparse
import sys
from arbitrer import Arbitrer
def patch_http_response_read(func):
def inner(*args):
try:
return func(*args)
except httplib.IncompleteRead as e:
return e.partial
return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
class ArbitrerCLI:
def __init__(self):
...

Resources