I'm setting up a new environment for a new project and I'm getting an SyntaxError: invalid syntax when running python manage.py runserver
Greater details
File "manage.py", line 16
) from exc
^
SyntaxError: invalid syntax
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', 'personal_portfolio.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()
It's like #Michael Butscher said, you're running it with python 2.0 and that is what is giving the problem.
Try running it like python3 manage.py. When you have both python 2 and python 3 installed in your system, running python runs python2.
Hope that helps.
I'm making a simple blog application on Django, using PyCharm as IDE.
If I try to use Python Console, I get this error every time.
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
If I open console command line in Terminal, I have to specify my settings using this command every time:
set DJANGO_SETTINGS_MODULE=mysite.settings
It looks like manage.py file already has a settings reference but for some reason it seems to be ignored:
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Example.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
...
In your PyCharm virtual environment. You have a option Edit Configurations, By click this a popup window is open. Then find Environment variable, and set DJANGO_SETTINGS_MODULE=Example.settings
I have been running my python server for a few months now and I have had no problems, but ever since I have installed react-native I now get the following error. I don't know if the python problem is related to the installation of react-native but it seems like a bit of coincidence.
Any help in solving this issue would be appreciated
File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax code here
My manage.py file:
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_website.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)
I fixed this my installing python 3.7 and running
py -3 manage.py runserver
I also had to reinstall the packages that were being used on my project
You are trying to use a Python-3-specific Django version with a Python 2 interpreter. You will clearly see that if you look at the top of the full stacktrace
raise ... from ... is a Python 3 syntax. A Python 2 interpreter will treat it as a SyntaxError as can be demonstrated here.
Make sure you are using Python 3 to execute this server.
After many researches on the web, on many different topics, I wasn't able to find the solution answering my problem.
I am developing a tool (with graphic interface) allowing to process python scripts from different projects.
To not have any problem of dependences, I ask the user to target the project directory as well as the script to process.
Thus to develop this tool I have in my IDE a project "benchmark_tool" which is the project integrating the GUI, and the project "test_project" which groups various testing scripts. Obviously, the final goal is the tool to be compiled and thus that the project "benchmark_tool" disappears from IDE.
Here is the IDE architecture:
benchmark_tool (python project)
__init__.py
main.py
test_project (python project)
__init__.py
module1
__init__.py
test_script.py
module2
__init__.py
imports.py
How it works: The main.py shall call test_script.py.
test_script.py calls imports.py at the first beggining of the script.
UPDATE
I tried some modifications in my main code:
import sys
import subprocess
subprocess.check_call([sys.executable, '-m', 'test_project.module1.test_script'], cwd='D:/project/python')
I got this error
Traceback(most recent call last):
File "C:/Python31/lib/runpy.py", line 110, in run module as main
mod_name, loader, code, fname = _get_module_detail(mod_name)
File "C:/Python31/lib/runpy.py", line 91, in get module details
code = loader.get_code(mod_name)
File "C:/Python31/lib/pkgutil.py", line 272, in get code
self.code = compile(source, self.filename, 'exec')
File "D:/project/python/test_project/module1/test_script.py", line 474
SyntaxError: invalid syntax
Traceback (most recent call last):
File "D:/other_project/benchmark_tool/main.py", line 187, in read
subprocess.check_call([sys.executable, '-m', 'module1.test_script.py'], cwd='D:/project/python/test_project')
File "C:/Python31/lib/subprocess.py", line 446, in check call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['C:/Python31/python.exe', '-m', 'module1.test_script.py']' returned non-zero exit status 1
Note
It works with subprocess.Popen(['python','D:/project/python/test_project/module1/test_script.py])
What's the main difference between both methods ? I'll also have to pass arguments to test_scripts.py, which one is the best to use to communicate with a python script (input and output datas are exchanged) ?
Thanks by advance
There are 3 problems I see that you have to fix:
In order to import from module2, you need to turn that directory into a package by placing an empty *__init__.py file in it
When executing test_script.py, you need the full path to the file, not just file name
Fixing up sys.path only work for your script. If you want to propagate that to test_script.py, set the PYTHONPATH environment variable
Therefore, my solution is:
import os
import sys
import subprocess
# Here is one way to determine test_project
# You might want to do it differently
script_dir = os.path.abspath(os.path.dirname(__file__))
test_project = os.path.normpath(os.path.join(script_dir, '..', 'test_project'))
python_path = '{}:{}'.format(os.environ.get('PYTHONPATH', ''), test_project)
python_path = python_path.lstrip(':') # In case PYTHONPATH was not set
# Need to determine the full path to the script
script = os.path.join(test_project, 'module1', 'test_script.py')
proc = subprocess.Popen(['python', script], env=dict(PYTHONPATH=python_path))
To run an "external project script", install it e.g.: pip install project (run it in a virtualenv if you'd like) and then run the script as you would with any other executable:
#!/usr/bin/env python
import subprocess
subprocess.check_call(['executable', 'arg 1', '2'])
If you don't want to install the project and it has no dependencies (or you assume they are already installed) then to run a script from a given path as a subprocess (assuming there is module1/__init__.py file):
#!/usr/bin/env python
import subprocess
import sys
subprocess.check_call([sys.executable, '-m', 'module1.test_script'],
cwd='/abs/path/to/test_project')
Using -m to run the script, avoids many import issues.
The above assumes that test_project is not a Python package (no test_project/__init__.py). If test_project is itself a Python package then include it in the module name and start from the parent directory instead:
subprocess.check_call([sys.executable, '-m', 'test_project.module1.test_script'],
cwd='/abs/path/to')
You could pass the path to test_project directory as a command-line parameter (sys.argv) or read it from a config file (configparser,json). Avoid calculating it relative to the installation path of your parent script (if you have to then use pkgutil, setuptools' pkg_resources, to get the data). To find a place to store user data, you could use appdirs Python package.
I've 2 separate settings files for production and development and a common base.py settings file
base.py
SECRET_KEY = r"!##$%^&123456"
prod.py
from .base import *
SECRET_KEY = os.environ['SECRET_KEY']
manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.dev")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
When I enter this in terminal:
python manage.py shell --settings=entri.settings.prod
I get error:
raise KeyError(key)
KeyError: 'SECRET_KEY'
Help me, I'm new to django and python
I think you are trying this locally, and don't have the SECRET_KEY setup in your environment.
Set it using
export SECRET_KEY="somesecretvalue"
and then running python manage.py shell --settings=entri.settings.prod should work fine.
I use os.getenv('SECRET_KEY'), instead of os.environ['SECRET_KEY']
print os.getenv('SECRET_KEY') #returns None if KEY doesn't exist
print os.getenv('SECRET_KEY', 0) #will return 0 if KEY doesn't exist
my python version is 2.7.12
In Django while trying to secure/hide my secret_key, my problem was even after setting the secret_key using the set command on windows, I still got a 'Key must not be empty' error. I solved that by removing all the spaces before and after the assignment operator in the command. In your cmd, write
set SECRET_KEY="kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
instead of
set SECRET_KEY = "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"