I want to enable debugging using visual studio debugging tool, ptvsd
. Using that I have to attach the debugger to the application using
ptvsd.enable_attach(address=(settings.REMOTE_URL, settings.DEBUG_PORT), redirect_output=True)
ptvsd.wait_for_attach()
Using ptvsd means I can't use threading and reloading, so I append the args
sys.argv.append("--nothreading")
sys.argv.append("--noreload")
For convenience to enable debugging I created an args to execute those line of codes. I created named argument debug
if __name__ == "__main__":
#previous line omitted
parser = argparse.ArgumentParser()
parser.add_argument("--debug", help="enable debugging through vscode")
args = parser.parse_args()
if args.debug:
sys.argv.append("--nothreading")
sys.argv.append("--noreload")
ptvsd.enable_attach(address=(settings.REMOTE_URL, settings.DEBUG_PORT), redirect_output=True)
ptvsd.wait_for_attach()
execute_from_command_line(sys.argv)
What I want to achieve is, when I want to debug my app I use the command
python manage.py runserver 0:8000 --enable-debugging
and when I just want to run my app I use python manage.py runserver 0:8000
but it returns an error when I tried to run using
python manage.py runserver 0:8000
it says unrecognized arguments for runserver
and 0:8000
by that, do I have to include all possible django positional argument to the parser
? and how to do that with the 0:8000
? add all possible port?
Is using named argument not viable for this case?
So apparently I can use parser.parse_known_args()
, it should be fine when there are unrecognized arguments. and because I want the --debug
as a flag, I add action='store_true'
in the add_argument so it returns true whenever the argument exists.
With that, I can solve this by using that and then remove the --debug
argument when passing it down to execute_from_command_line
. Something like this:
if __name__ == "__main__":
#previous line omitted
parser = argparse.ArgumentParser()
parser.add_argument("--debug", action='store_true', help="enable debugging through vscode")
args = vars(parser.parse_known_args()[0])
if args.debug:
sys.argv.append("--nothreading")
sys.argv.append("--noreload")
ptvsd.enable_attach(address=(settings.REMOTE_URL, settings.DEBUG_PORT), redirect_output=True)
ptvsd.wait_for_attach()
execute_from_command_line(sys.argv)
Now it works :)