Why is VSCode Python terminal misinterpreting Python code and executing uncalled functions? - python

I'm running a Conda environment on VSCode and when I Shift-Enter to run main.py , a new Python terminal opens and runs the script, but functions are executing without being called and I'm getting a :
SyntaxError: 'return' outside function
Despite the indentation being seemingly fine.
import math
def h(x):
if x==0:
return 1
else:
return 2*math.sin(x)/x - 1
The above returns:
(base) josh#Joshs-Macbook Coursework1 % source /Users/josh/opt/anaconda3/bin/activate
(base) josh#Joshs-Macbook Coursework1 % conda activate base
(base) josh#Joshs-Macbook Coursework1 % /Users/josh/opt/anaconda3/bin/python
Python 3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> return 2*math.sin(x)/x - 1
File "<stdin>", line 1
SyntaxError: 'return' outside function
>>>

You have executed the command of Run Selection/Line in Python Terminal with the shortcut of Shift+Enter. You can select the command of Run Python File in Terminal which is above it.

Shift+Enter is keybindings for Run Selection/Line in Python Terminal, so if you put cursor in the line of return 2*math.sin(x)/x - 1, it will throw errors:
If you want to enter interactive mode then run the function h(x), please
type python in integrated Termial;
import filename. In my case, it's a.py so i import a;
call the function: a.h(any number)
exit interactive mode;
Or you can get result directly by adding print(h(any number)), then clicking the triangle button in top right corner to run python file in integrated Terminal. Get the same result:

run the entire code in python as opposed to the last line.
if you want to run entire scripts:
python3 xxxx.py

Related

NameError with first python script

Using just notepad I typed out:
print ('hello world')
and saved it under ThisPC>windows(C:)>Users>me>Anaconda3 as:
first_program.py
Now I'm in Anaconda Prompt, I typed in Python and got back:
Python 3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
But when I try to run the script I thought I made, by typing in (without quotes) "first_program.py" I get back an error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'first_program' is not defined
I have no clue what's causing it. So far I've tried changing the syntax of the script, like:
print 'hello world'
print "hello world"
print (hello world)
print ("hello world")
and other variations with the parentheses and keep getting the same error message.
Please help me understand what I'm doing wrong.
When you type in python in anaconda prompt, it launches the python interpreter. Any Python code written in this context while be read and executed.
When you type in "first_program.py" within the context of the interpreter, it will rightly raise a NameError as in the context of the interpreter, this reference does not exist.
However, if you were to simply type in the python command print('hello world') and hit enter, the interpreter will render the output correctly and print 'hello world' on your terminal.
To run the python script, simply open a terminal or Anaconda Prompt (navigate to the directory in which the python script resides) and run your script by typing either python first_program.py or first_program.py.
Assuming you're on the command line, and in the same directory as first_program.py
you can do:
python first_program.py
This will start python with your file as what you want it to run and then exit when it is complete.

Why doesn't python send output to stdout?

Here's a minimum working example (MWE), saved as mwe.py:
import sys
def f(n):
print("Testing print()...")
sys.stdout.write("Calculating f({})...".format(n))
When run from the command line I get no output whatsoever:
username#hostname:~/mydir$ python mwe.py 'f(99)'
username#hostname:~/mydir$
When run from within python
I get output (some info removed):
username#hostname:~/mydir$ python
Python 3.5.4 (default, DATE, HH:MM:SS)
[GCC X.X.X Compatible Apple LLVM X.X.X (clang-X.X.X)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from mwe import f
>>> f(99)
Testing print()...
Calculating f(99)...
>>>
Why do these output statements work within python but not from the command line?
python mwe.py 'f(99)' doesn't mean "run the f function from mwe.py with argument 99". If you wanted to do that from the command line, you could execute
python -c 'import mwe; mwe.f(99)'
python mwe.py 'f(99)' means "run the script mwe.py with sys.argv[1] set to the string "f(99)"". The script mwe.py doesn't examine sys.argv or print anything at all; it just defines a function and ends.
This: python mwe.py 'f(99)' just shouldn't work. In this case, 'f(99)' is just passed as an argument to the program.
Try using python -c 'import mwe; mwe.f(99) instead. (also read more about command line usage of python by typing python -h)

In the Python debugger pdb, how do you exit interactive mode without terminating the debugging session

Using python 3.5.1
When I run a script using the python debugger module:
[home]# python -m pdb myscript.py
This starts a debug session:
> /somepath/to/myscript.py(1)<module>()
-> import os
(Pdb)
If I want to enter an interactive terminal from within the debug session I can issue the interact command:
(Pdb) interact
*interactive*
>>>
Now I can interact with th code as if I was in a running python interactive mode, with access to any functions or variable in scope of the script running in the debugger at the time I entered interact mode.
When I issue the command to exit the interactive mode (to continue debugging) it kills the entire debug session:
>>> exit()
The program exited via sys.exit(). Exit status: None
....long nasty stack trace here....
[home]#
I've also tried quit() and it also terminates the debugger.
How can you exit out of interact mode without terminating the entire debug session? Is this even possible?
Ideally, I'd like to return to into debug mode at the point where I left off so I could continue stepping through my code.
Sending an EOF by pressing Ctrl + D should work:
$ python -m pdb myscript.py
> .../myscript.py(1)<module>()
-> import os
(Pdb) import code
(Pdb) code.interact()
Python 2.7.11 (default, Dec 27 2015, 01:48:39)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> <CTRL-D>
(Pdb) c
...
If you are using ipdb, and are on Windows/Windows10, you should use Cntrl-Z>Return to get out of the interactive shell.
Tested in ipython/python 3.5 and ipdb and pdb
For those who look for a solution in jupyter notebook (and just yet do not want to learn emacs). I found one which worked for me (from here).
In linux shell:
echo ^D | xclip -selection clipboard
But, you do NOT type ^D as characters but as ctrl-v ctrl-d...
https://github.com/jupyter/notebook/issues/3603#issuecomment-747392494
from pandas.io.clipboard import copy; copy("\x04")
Copies Ctrl-D to your clipboard, and the you can paste it and enter.
If you're using Emacs and accessing the pdb interact mode through M-x shell, the best I could find was to call comint-quit-subjob (C-c C-\). This kills the entire debug session and returns you to the shell session rather than killing the entire shell process as comint-send-eof (C-c C-d) would do.
(venv) c:\projects\my-project> python my-entry-point.py
550 import ipdb; ipdb.set_trace(context=10)
--> 551 print("First line to start debugging at")
ipdb> interact
*interactive*
In : # call M-x comint-quit-subjob (C-c C-\)
^C
(venv) c:\projects\my-project>
In my version of Spyder (on Gnome), I cannot type Ctrl+D or Ctrl+Shift+U. So to escape interactive mode, I open a text editor, type Ctrl+Shift+U then, without letting go of Ctrl+Shift, I press Ctrl+Shift+4. This places a character in the text editor that I can highlight and copy. I then paste it into the interactive mode of Spyder and I can get out of interactive mode and back into the debugger.
On Windows 10, press Ctrl + Z and give Enter.
In Python 3, use the Interactive Interpreter:
(Pdb) code.interact()
>>> (Enter your commands)
>>> ...
>>> exit() # Exit interactive mode
(Pdb) c
You can also import "code" in your main code and just use code.interact() in "Pdb" mode.
Re: https://docs.python.org/3/library/code.html
(Note: exit() doesn't work in interactive mode in Python 2)
On a related note, if you want to exit the debugger entirely you just press q then enter.

Python error "import: unable to open X server"

I am getting the following errors when trying to run a piece of python code:
import: unable to open X server `' # error/import.c/ImportImageCommand/366.
from: can't read /var/mail/datetime
./mixcloud.py: line 3: syntax error near unexpected token `('
./mixcloud.py: line 3: `now = datetime.now()'
The code:
import requests
from datetime import datetime,date,timedelta
now = datetime.now()
I really lack to see a problem. Is this something that my server is just having a problem with and not the code itself?
those are errors from your command shell. you are running code through the shell, not python.
try from a python interpreter ;)
$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> from datetime import datetime,date,timedelta
>>>
>>> now = datetime.now()
>>>
if you are using a script, you may invoke directly with python:
$ python mixcloud.py
otherwise, ensure it starts with the proper shebang line:
#!/usr/bin/env python
... and then you can invoke it by name alone (assuming it is marked as executable):
$ ./mixcloud.py
Check whether your #! line is in the first line of your python file. I got this error because I put this line into the second line of the file.
you can add the following line in the top of your python script
#!/usr/bin/env python3
I got this error when I tried to run my python script on docker with docker run.
Make sure in this case that you set the entry point is set correctly:
--entrypoint /usr/bin/python

Why can't Python find and run my scripts when calling Python from Python command line?

I am in the python command line (using python 2.7), and trying to run a Python script. My operating system is Windows 7. I have set my directory to the folder containing all of my scripts, using:
os.chdir("location").
os.getcwd() returns this location.
When I type:
python myscript.py
I get this error:
File "<stdin>", line 1
python myscript.py
^
SyntaxError: invalid syntax.
What have I done wrong?
The first uncommented line of the script I'm trying to run:
from game import GameStateData
It sounds like you're trying to run your script from within Python. That's not how it works. If you want to run myscript.py, you need to do it from a system command prompt, not from inside the Python interpreter. (For instance, by choosing "Command Prompt" from your start menu. I think it's usually under "Accessories" or something like that.) From there you'll need to change to the directory where your scripts are by using the CD command.
Based on the additional information you have provided it does look like you are issuing the command inside of Python.
EDIT: Maybe part of the confusion comes from the term command line. You are at the command line in both the "Windows command" shell, and also when you are inside the "Python shell".
This is what I get in the command line when inside the Python shell:
D:\Users\blabla \Desktop>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python testit.py
File "<stdin>", line 1
python testit.py
^
SyntaxError: invalid syntax
>>>
Or this:
>>> os.chdir("..")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
My suggestion would be to open a Windows command shell window with the cmd command and then issue your python myscript.py from there.
For more help it would be helpful to see your code, at least the first few lines where the error occurs and some certainty as to where the python command is being issued.
As the other answers indicate, you are probably in the Python shell unintentionally. But if you really do want to run your script from there, try execfile("myscript.py")
on windows shell run echo %PATH%, and check if your .py is under any of the paths.

Categories