ModuleNotFoundError in vs code Frappe import - python-3.x

Unfortunately, I always get this error message with Frappe, so I ask you that you can maybe help me and give me a few types. Thank you and I'll be happy to wait for your answer. Thanks
Error:
Exception has occurred: ModuleNotFoundError
No module named 'frappe'
File "/home/erp/frappe-bench/apps/erpnextfints/erpnextfints/erpnextfints/doctype/fints_import/fints_import.py", line 7, in
import frappe
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import now_datetime, get_datetime
Import "frappe.model.document" could not be resolvedPylancereportMissingImports***`
# -*- coding: utf-8 -*-
# Copyright (c) 2019, jHetzer and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import now_datetime, get_datetime
class FinTSImport(Document):
def validate_past(self, date, field_name):
if isinstance(date, str):
date = get_datetime(date).date()
if date >= now_datetime().date():
frappe.msgprint(
_("'{0}' needs to be in the past").format(field_name)
)
return False
if (now_datetime().date() - date).days >= 90:
frappe.msgprint(
_("'{0}' is more then 90 days in the past").format(field_name)
)
return False
return True
def before_save(self):
status = True
if self.from_date is not None:
status = self.validate_past(self.from_date, "From Date")
if self.to_date is not None:
from_date = get_datetime(self.from_date).date()
if from_date > get_datetime(self.to_date).date():
status = False
frappe.msgprint(_(
"'From Date' needs to be further in the past"
" then 'To Date'"))
if self.to_date is not None:
if not self.validate_past(self.to_date, "To Date"):
status = False
if not status:
frappe.throw(_("Validation of dates failed"))
def validate(self):
self.before_save()
Screenshot of VS Code:

Each Bench has it's own Python env which is where Frappe apps & their Python dependencies are installed. This directory can be found under the respective bench's root - /home/erp/frappe-bench in your case.
You have tell VS Code to use the Python interpreter from that environment. You can do that by either
Manually setting the interpreter for your session
You may follow the instructions mentioned in the docs or this YouTube video.
Changing your current working directory
Simply cd into your bench and open VS Ccode from there - cd /home/erp/frappe-bench && code . and VS Code detects the env folder automatically and uses it as the active interpreter.

Related

What is the SyntaxError in the a "def" line in a python script?

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!

How do I stop argparser from printing default search?

Link to my code: https://pastebin.com/y4zLD2Dp
The imports that have not been used are going to be used as I progress through my project, I just like to have all imports I need ready to go. The goal for this program will be a youtube video downloader into mp3 format first. This is my first big project to my standards, only been coding for just over 2 months.
from bs4 import BeautifulSoup
from selenium import webdriver
import requests
import sqlite3
import argparse
import sys
from selenium import webdriver
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
#To get a developer key visit https://console.developers.google.com.
DEVELOPER_KEY = ""
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
'''Searches for results on youtube and stores them in the database.'''
def yt_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search = youtube.search().list(q=options.q, part="id,snippet",
maxResults=options.max_results).execute()
video_id = []
#Add results to a list and print them.
for result in search.get("items", []):
if result["id"]["kind"] == "youtube#video":
video_id.append("%s (%s)" % (result["snippet"]["title"],
result["id"]["videoId"]))
else:
continue
print("Videos:\n", "\n".join(video_id), "\n")
def download(args):
print(args)
"""Arguments for the program."""
if __name__ == '__main__':
parser = argparse.ArgumentParser(description= "This program searches for
Youtube links and allows you to download songs from said list. " +
"Please remember to be specific in your
searches for best results.")
parser.add_argument("--q", help="Search term", default="Aeryes")
parser.add_argument("--max-results", help="Max results", default=25)
parser.add_argument("--d", type=download, help="Download a video from
search results.")
args = parser.parse_args()
if len(sys.argv) < 2:
parser.parse_args(['--help'])
sys.exit(1)
try:
yt_search(args)
except HttpError:
print("HTTP error")
The problem that I am having is that upon running the --d cmd in the CLI it works and prints the arg as expected (This is just a test to see that functions are working with the parser) but after it prints a list of default youtube links from --q default which I do not want it to do. How do I stop this from happening. Should I use subparser or is there something that I am missing?
If anyone has good resources for argparser module other than official doc support please share.

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.

Nmap7.5:how to add scripts into its path except /usr/share/nmap/scripts

I once installed nmap7.1 on my Ubuntu and added some nse scripts into its path /usr/share/nmap/scriptsbut when I remove nmap7.1 and install nmap7.5 with the official source and compiled myself ,I find there is a few nse scripts which are those I once added and the nmap command can not using these scripts.But my python programs need these nse scripts ,so my question is where should these nse scripts added to OR which command could add this nse scripts into Nmap Path and working properly.Thanks !
I have resolved my problem:this is my cocument structure:
scan_s/nse/modicon-info.nse
/namp.py
this my python script:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from libnmap.process import NmapProcess
from time import sleep
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import sys
nmap_proc = NmapProcess(targets="45.76.197.202", options="--script nse/s7-info.nse -p 102")
nmap_proc.run_background()
while nmap_proc.is_running():
sleep(2)
xml = nmap_proc.stdout
print xml
xmlfiled = open('testxml.xml','w')
xmlfiled.write(xml)
xmlfiled.close()
try:
tree = ET.parse('testxml.xml')
root = tree.getroot()
test = root.find('host').find('ports').find('port').find('script')
test_dic = dict(test.attrib)
s = test_dic['output']
except:
s = 'unknown'
print s
hope it can help you :)

problems with PyQt4 and Python 3.5

I'm using python 3.5.1 64 bit.
My operating system is Windows 10.
I installed: pip install PyQt4-4.11.4cp35-none-win_64.whl from gohlke site.
pip says it was installed successfully.
I can import PyQt4 but none of the modules in it.
It is installed in site-packages.
When I open the PyQt folder I find: QtCore.pyd and QtCore.dll, but when I try to import them I get a message that they aren't found. The program is from Summerfield's book. Here it is:
import sys
import time
import PyQt4
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = QApplication(sys.argv)
try:
due = QTime.currentTime()
message = "Alert!"
if len(sys.argv) < 2:
raise ValueError
hours, mins = sys.argv[1].split(":")
due = QTime(int(hours), int(mins))
if not due.isValid():
raise ValueError
if len(sys.argv) > 2:
message = " ".join(sys.argv[2:])
except ValueError:
message = "Usage: alert.pyw HH:MM [optional message]" #24hr clock
while QTime.currentTime() < due:
time.sleep(20)
label = QLabel("<font color=red size=72><b>" + message + "</b></font>")
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000, app.quit)
app.exec()
I solved this problem. I didn't have msvcp140. Install Visual C++ Redistributable for Visual Studio 2015 and propably will be fine. I also changed PyCharm version to 4.5.4

Resources