Vscode python file runs fine but ModuleNotFoundError is thrown when code-runner is used - python-3.x

Hello I have the following directory structure for my project in vscode:
--- my_programs/----|
|--my_code/----|
|__tests/
|
|__libs/my_package/classes.py
|
|__main/main.py
When I run main.py in the vscode terminal it runs fine. As soon as I run it using "Run Code" (which is an extension) it complains about the following:
`
Running] /Users/username/my_programs/venv/bin/python -u "/Users/username/my_programs/my_code/main/main.py"
Traceback (most recent call last):
File "/Users/username/my_programs/my_code/main/main.py", line 2, in <module>
from libs.my_package.classes import MyClass
ModuleNotFoundError: No module named 'libs'
`
main.py looks like this:
import os
from libs.my_package.classes import MyClass
dir_path = os.path.dirname(os.path.realpath(__file__))
print (dir_path)
cwd = os.getcwd()
print(cwd)
os.chdir(dir_path)
cwd = os.getcwd()
print (cwd)
m = MyClass("Hello Hello")
print(m)
My settings.json looks like the following:
{
"terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}/my_code"},
"python.envFile": "${workspaceFolder}/.vscode/env",
"python.analysis.extraPaths": [
"my_programs",
],
"python.testing.pytestArgs": [
"my_code"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.testing.cwd": "${workspaceFolder}",
"python.terminal.activateEnvironment": true,
"python.terminal.activateEnvInCurrentTerminal": true,
"code-runner.fileDirectoryAsCwd": false,
"code-runner.executorMap":
{
"python": "$pythonPath -u $fullFileName"
},
}
Why does it work when I click "Run Python File" and not when I do "Run Code"? FYI, it also works manually from the terminal.

Related

youtube_dl KeyError 'key'

Hello I am trying to download youtube videos with the following code
import youtube_dl
import tempfile
youtube_links = ['https://www.youtube.com/watch?v=668nUCeBHyY']
with tempfile.TemporaryDirectory() as tempdir:
opts = {
'format': 'best',
'outtmpl': f'{tempdir}/%(id)s.%(ext)s',
'noplaylist': True,
'postprocessors': [{
'preferredcodec': 'mp4'
}]
}
ydl = youtube_dl.YoutubeDL(opts)
try:
meta = ydl.extract_info(
youtube_links,
download=True
)
except Exception as e:
raise e
else:
print(f"Downloaded to {tempdir}/{meta['id']}.{meta['ext']}")
However this raises an error:
<path>>py -3.8 test.py
Traceback (most recent call last):
File "test.py", line 14, in <module>
ydl = youtube_dl.YoutubeDL(opts)
File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\youtube_dl\YoutubeDL.py", line 429, in __init__
pp_class = get_postprocessor(pp_def_raw['key'])
KeyError: 'key'
And none of the examples told me anything about a key I have to pass, nor can I find anything about it, what am I doing wrong?
In a nutshell, try this:
'postprocessors': [{
'key':'FFmpegMetadata',
'preferredcodec': 'mp4'
}]
There are lots of keys, so if it's not working, check out this: https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/postprocessor/__init__.py
The trick is that the keys listed inside the file are not usable because you gotta drop the "PP" part!!
FYI:
It seems you are trying to get video? Then you should try the documented style: https://github.com/ytdl-org/youtube-dl/
You have to look at the "Functions" yourself and guess what parameters you should put here: https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/YoutubeDL.py In fact, somewhere in this link says, "check out the init.py for key information."

Jenkins ImportError module not found

I have a file structure like this:
Main/
|----unit_tests
| |---test_main.py
| |---__init__.py
|--main.py
|--__init__.py
|--requirements.txt
test_main.py:
import unittest.mock
from main import MainFunction
from nose.tools import assert_is_not_none, assert_is_none, assert_equal
class TestMainLogic(unittest.case):
~~~ code here ~~~~
When running my unit tests in test_main.py from Pycharm, all is well. However when I try to run it in a Jenkins setup, I get:
+ python3 unit_tests/test_main.py
Traceback (most recent call last):
File "unit_tests/test_main.py", line 4, in <module>
from main import MainFunction
ModuleNotFoundError: No module named 'main'
Here's my Jenkinsfile:
pipeline
{
environment
{
PATH = "/home/jenkins/.local/bin:$PATH"
}
stages
{
stage('build')
{
steps
{
sh 'python3 --version'
sh 'wget https://bootstrap.pypa.io/get-pip.py'
sh 'python3 get-pip.py'
sh 'pip3 install -r requirements.txt'
echo 'build phase has finished'
}
}
stage('Lint')
{
steps
{
sh 'pylint unit_tests/test_main.py'
}
}
stage('test')
{
steps
{
sh 'python3 unit_tests/test_main.py'
}
post
{
always
{
cleanWs()
}
}
}
}
}
I've followed several posts and I'm just not getting an answer that works. I tried:Python module import failure in Jenkins and its linked answers. I do not have access to ssh into the Jenkins server and find the path so I need a way to set it at execution.
you need to use absolute import instead of relative in your test_main.py file.
in test_main.py
replace:
from main import MainFunction
# SOME CODE
with:
from Main.main import MainFunction
# SOME CODE

The run time error by import python module

I am trying to make correctly import the function "mmenu" from another module
I got a run time error:
Traceback (most recent call last):
File "path.../venv/src/routes.py", line 4, in <module>
from venv.src.main_menu import mmenu
ModuleNotFoundError: No module named 'venv.src'
after Java this Python is a bit of a mystery to me :)
I have 2 files in the same "src" directory
main_menu.py
def mmenu():
menu = [{"name": "HOME", "url": "home"},
{"name": "fooo", "url": "foo"},
{"name": "bar", "url": "bar"},
{"name": "CONTACT", "url": "contact"}]
return menu
routes.py
from flask import Flask, render_template, request, flash, session, redirect, abort
from jinja2 import Template
from flask.helpers import url_for
from venv.src.main_menu import mmenu
app = Flask(__name__)
menu = mmenu
#app.route("/")
#app.route("/index")
def index():
# return "index"
print("loaded" + url_for('index'))
return render_template('index.html', title="Index page", menu=menu)
# ...
if __name__ == "__main__":
app.run(debug=True)
import was generated by IDE like:
from venv.src.parts.main_menu import mmenu
Your IDE (which IDE?) is likely misconfigured if it generates imports like that.
The venv itself, nor any src directory within them, shouldn't be within import paths.
You never mention you have a parts/ package, but from the import I'll assume you do, and your structure is something like
venv/
src/ # source root
routes.py
parts/ # parts package
__init__.py # (empty) init for parts package
main_menu.py
With this structure, main_menu is importable as parts.main_menu from routes.py assuming you start the program with python routes.py.
If you have __init__.py files in venv/ and/or src/, get rid of them; you don't want those directories to be assumed to be Python packages.

CX_Freeze : Import error : _ufuncs_cxx

I am currently using Python 3.4 on my windows 10 64x and trying to freeze my application using CX_Freeze. Unfortunetly, I get an error message : "Import error : No module named scipy.special._ufuncs_cxx".
Here is my setup.py :
# -*- coding: Latin-1 -*-
import sys
import scipy
from cx_Freeze import setup, Executable
import PyQt4
packages=['PyQt4.QtCore', 'PyQt4.QtGui', 'sys', 'socket', 'pprint', 'pandas', 'datetime', 'json','numpy', 'scipy']
include_files=['C:/Users/sadid/OneDrive/Documents/Visual Studio 2015/Projects/db/img/lib-ico.ico',
'C:/Users/sadid/OneDrive/Documents/Visual Studio 2015/Projects/Lib/db/img']
if sys.platform == 'win32':
base = 'Win32GUI'
exe = Executable(
script='C:/Users/sadid/OneDrive/Documents/Visual Studio 2015/Projects/Lib/Lib/main.py',
initScript = None,
base=base,
targetName='Lib.exe',
copyDependentFiles = True,
compress = True,
icon='C:/Users/sadid/OneDrive/Documents/Visual Studio 2015/Projects/LibAppCustomer/LibAppCustomer/db/img/lib-ico.ico'
)
setup(
name ='LibApplication',
version = '1.0.0',
description = 'Pricing\'s Application',
author = 'DIKSA',
executables = [exe],
options = {
"build.exe": {
"packages": packages,
'include_files': include_files,
'includes' : ['scipy.special._ufuncs_cxx']
}
}
)
Any help please guys thx
This issue is based on how scipy loads itself and there is a plan in place to have cx_Freeze handle these and other such issues -- but it is still in progress. The comments in this issue, however, can help you workaround the issue for now:
https://bitbucket.org/anthony_tuininga/cx_freeze/issues/43/import-errors-when-using-cx_freeze-with

Using cx_freeze in PyQt5, can't find PyQt5

I want to build a standalone binary file for windowz(xp, 7, ...) from my python3(+ PyQt5) script and I inevitably use cx_freeze because other freezing apps do not work with python3 (like py2exe, pyinstaller).
I read the cx_freeze docs and lots of stackoverflow asks ans use this config for setup.py‍‍‍ file :
import sys
from cx_Freeze import setup, Executable
path_platforms = ( "C:\Python33\Lib\site-packages\PyQt5\plugins\platforms\qwindows.dll", "platforms\qwindows.dll" )
includes = ["atexit","PyQt5.QtCore","PyQt5.QtGui", "PyQt5.QtWidgets"]
includefiles = [path_platforms]
excludes = [
'_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger',
'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl',
'Tkconstants', 'Tkinter'
]
packages = ["os"]
path = []
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {
"includes": includes,
"include_files": includefiles,
"excludes": excludes,
"packages": packages,
"path": path
}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
exe = None
if sys.platform == "win32":
exe = Executable(
script="D:\\imi\\aptanaWorKPCworkspace\\azhtel\\tel.py",
initScript = None,
base="Win32GUI",
targetDir = r"dist",
targetName="tel.exe",
compress = True,
copyDependentFiles = True,
appendScriptToExe = False,
appendScriptToLibrary = False,
icon = None
)
setup(
name = "telll",
version = "0.1",
author = 'me',
description = "My GUI application!",
options = {"build_exe": build_exe_options},
executables = [exe]
)
run with:
python D:\imi\aptanaWorKPCworkspace\azhtel\setup.py build
This is my library that I used:
from PyQt5 import QtGui, QtCore, QtWidgets
import sys
from telGui import Ui_MainWindow
import mysql
import mysql.connector
from mysql.connector import errorcode
and this is my files in workspace:
But this error happened (or another kind of errors).
Why this happened and what config for setup.py is good for pyqt5 app ??
Thanks.
Python3.3, PyQt5, Mysqlconnector.
I solved this problem with find another directory near the dist directory called build and all library files are in there, i delete targetDir = r"dist" part of setup.py and everythings is alright !
Try pyinstaller. It's much better than cxfreeze.

Resources