Problem :- My aim is to create a python file that will set-up virtual enviroment and will activate virtual enviroment by calling setup_env.py file.
In cmd,
python setup_env.py
with this line i am calling my file and this will setup virtual env automatically.
import os
import sys
import subprocess
def create_venv():
subprocess.check_call([sys.executable, "-m", "venv", "env"])
def activate_venv():
if os.name == 'nt': # for windows
activate_script = os.path.join("env", "Scripts", "activate.bat")
else: #Unix/Linus/MacOS
activate_script = os.path.join("env", "bin", "activate")
activate_this = os.path.abspath(os.path.join(os.getcwd(), activate_script))
with open(activate_this) as f:
code = compile(f.read(),activate_this,'exec')
exec(code,dict(__file__=activate_this))
if __name__ == '__main__':
create_venv()
activate_venv()
Now after this my virtual enviroment is generated and activated also, but in cmd i am getting this error, as follows :-
PS C:\Setup_env> python .\Setup_env.py
Traceback (most recent call last):
File "C:\Setup_env\Setup_env.py", line 20, in <module>
activate_venv()
File "C:\Setup_env\Setup_env.py", line 15, in activate_venv
code = compile(f.read(),activate_this,'exec')
File "C:\Setup_env\env\Scripts\activate.bat", line 1
#echo off
^
SyntaxError: invalid syntax
Related
There was an error account.User that has not been installed
but I solved this problem. After that, another error says The SECRET_KEY setting must not be empty.
I don't know whether my method to solve this problem is correct or not, I applied some solutions with Google.
But now, there is an error ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
But I already installed django and virtualenv. I don't know how to do it.
Recent error:
Traceback (most recent call last):
File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 10, in main
from django.core.management import execute_from_command_line
File "/Users/leejunseo/PycharmProjects/ITM coding/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 12, in <module>
from django.conf import settings
File "/Users/leejunseo/PycharmProjects/ITM coding/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 21, in <module>
from .base import *
ModuleNotFoundError: No module named 'django.conf.base'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 21, in <module>
main()
File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 12, in main
raise ImportError(
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
MY code manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tothegemList.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
__init__.py
import functools
import os
import pkgutil
import sys
from argparse import _SubParsersAction
from collections import defaultdict
from difflib import get_close_matches
from importlib import import_module
import django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import (
BaseCommand, CommandError, CommandParser, handle_default_options,
)
from django.core.management.color import color_style
from django.utils import autoreload
def find_commands(management_dir):
"""
Given a path to a management directory, return a list of all the command
names that are available.
"""
command_dir = os.path.join(management_dir, 'commands')
return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
if not is_pkg and not name.startswith('_')]
.
.
.
conf/__init__py
import warnings
from pathlib import Path
import django
from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import LazyObject, empty
from .base import *
env_name = os.getenv('ENV_NAME', 'local')
if env_name == 'prod':
from .prod import *
elif env_name == 'stage':
from .stage import *
else:
from .local import *
ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
Your traceback is telling you exactly what is wrong :
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
So you should relaunch your IDE or activate your environnement, as Django cannot be launch
I am using a Mac OSX 10.13.6. I have Python 3.9 installed.
I activated my venv, then installed Django. When I use 'pip list' or 'pip3 list', it lists Django as one of the Python packages that are installed. In addition, I was able to create a project using "django-admin startproject . If Django was not installed or I was not using venv, then I could not execute the django-admin command.
Also, I checked the venv/lib/python3.9/site-packages and django and other Python packages are installed in that directory. AND I did
'export PYTHONPATH=/Library/Frameworks/Python.framework/Versions/3.9'.
So, it is somewhat confusing why python3 is not finding Django. Any suggestions?
I installed django through this command
pip install django
I created a small app to download youtube videos and add them to my music folder so I can listen to them via spotify, app works fine as long as I run it via IDE.
I created an .exe file via pyinstaller, however it crashes on launch, I tried running it as administrator and also tried running it via cmd as people suggested in other threads, but nothing works.
I created it by using:
pyinstaller --onefile -c test.py
This is the python code:
from pytube import YouTube
from pytube import Playlist
from moviepy.editor import *
from pathlib import Path
import os
url = input('Enter URL: ')
ytd = YouTube(url)
stream = ytd.streams.first().download(filename= 'video') #stiahne do root filu
mp3_file = ytd.title + '.mp3' #meno pesnicky
#videoClip = VideoFileClip('video.mp4')
audioClip = VideoFileClip('video.mp4').audio
audioClip.write_audiofile(mp3_file) #mp4 na mp3
audioClip.close()
VideoFileClip('video.mp4').close() #v root file je mp3 a mp4
os.remove('video.mp4') #zmaze mp4, ostane mp3
file_path = str(os.path.dirname(os.path.realpath(mp3_file))) + '\\' + mp3_file
music_path = str(os.path.join(Path.home(), "Music")) + '\\' + mp3_file
Path(file_path).rename(music_path)
This is what I get one I try to run it via cmd:
Traceback (most recent call last):
File "C:\Users\rporu\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\PyInstaller\loader\rthooks\pyi_rth_pkgres.py", line 13, in <module>
import pkg_resources as res
File "c:\users\rporu\appdata\local\programs\python\python38-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
exec(bytecode, module.__dict__)
File "site-packages\pkg_resources\__init__.py", line 86, in <module>
ModuleNotFoundError: No module named 'pkg_resources.py2_warn'
[3296] Failed to execute script pyi_rth_pkgres
while creating exe use the hidden import
pyinstaller --hidden-import=pkg_resources.py2_warn --onefile -c test.py
i'm using rpy2 in spyder 4. all commands are working fine in console. i created an executable with pyinstaller and i got this error in exe file.
Traceback (most recent call last):
File "kopa.py", line 12, in <module>
ModuleNotFoundError: No module named 'rpy2'
[13148] Failed to execute script kopa
I will give an example to be short;
import os
os.environ['R_HOME'] = 'C:/Program Files/R/R-3.6.3'
os.environ['R_USER'] = 'C:/ProgramData/Anaconda3/Lib/site-packages/rpy2'
import rpy2.robjects as ro
ro.r("x=c(1,2,3,4,5)")
ro.r("y=c(11,12,13,14,15)")
ro.r("z=mean(x)+mean(y)")
print(ro.r("z"))
all working fine in console. when i create executable file then i'm getting the above error. where is the problem?
My script is working fine if I run it as Python from the command line.
I have converted the script to an .exe and am facing an issue with xlswrite. Below is the error output:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in <module>
exec code in m.__dict__
File "loader.py", line 5, in <module>
ImportError: No module named xlsxwriter
I have used this video to create the .exe for my Python script.
How should I fix the import error?
I have only used cx_freeze a few times and was successful using these steps. You were possibly missing something in this. First, create a setup.py like so:
from cx_Freeze import setup, Executable
import sys
exe = Executable(
script="yourmodule.py",
base="Win32GUI",
)
setup(
name = "desiredname",
version = "1",
description = "example program",
executables = [exe]
)
Before running this, make sure that you have all non-default (built-in) modules and the setup.py file in the same folder as the yourmodule.py file. Then from the command line, run python setup.py build.
I have installed wexpect on Windows 7. Now, when I am trying to run any command, I am getting the below error. I am using MKS toolkit, so ls is a valid command.
>>> import pexpect
>>> pexpect.run('ls ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line
219, in run
child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line
429, in __init__
self._spawn (command, args)
File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line
516, in _spawn
raise ExceptionPexpect ('The command was not found or was not executable: %s
.' % self.command)
pexpect.ExceptionPexpect: The command was not found or was not executable: ls.
Can some one please help?
Very late reply, but I also faced this problem recently.
Many reasons for failure or probably, wexpect.py needs modification (at least for my case)
Pl check pexpect_error.txt file generated in the same directory of wexpect.py file.
It forks 'python.exe' hence 'python.exe' must be in path (no other name of exe is permitted).
You must be in the same directory of wexpect.py (lib file name must be wexpect.py not pexpect.py) when you are executing your py script.
The cmd (with extension .exe/.com/.bat), must be working at your windows/shell command prompt . Check that (eg actually in Windows when we run 'ls', it is actually running ls.exe/com, in py script, mention as 'ls.exe')
Last but not least: In my case, console window for Window OS creation was failing (found from pexpect_error.txt), hence I changed below
line 2397, make Y coordinate of rect small instead of 70 eg 24 worked for me
UPDATE
The issue has already solved in v2.3.4.
Brief:
Add .exe at the end of the executable:
>>> import pexpect
>>> pexpect.run('ls.exe')
Details:
The root cause of the problem placed in the enumerated which command (method). This method searches the executable in the filesystem. Here is the critical snippet from my wexpect:
# ...
for path in pathlist:
f = os.path.join(path, filename)
if os.access(f, os.X_OK):
return f
return None
# ...
This code appends the parameter of run() as filename and returns it if it is a valid and executable path. Note, that Windows (unlike Linux) executables ends with *.exe