Execute a PyDev project in the Python Interactive Console? - python

I'm a begginer in Python and PyDev. I recently made the "helloworld" program in PyDev. My question is: how do I execute it or open it in the interactive Python mode (in Linux terminal) I tried many commands, like ./hello.py, import hello.py, python hello.py, but the only thing I got was SyntaxError: invalid syntax, or some other error.
I also have another question. I have Linux and I opened Eclipse in the terminal (sudo eclipse).
In PyDev, I first went to
File => New => Python Project => HelloWorld (name of project) =>
right click the project => New => PyDev Module => hello (module name).
It is assumed that the name I put in the terminal (running Python) is that of the module, no? Either way, I also tried with the name of the project and nothing. Just to know.
And, when do I use chmod +x? Every time I write it in PyDev, I get an X on the left, which means it's incorrect. Something like this: X chmod +x.

I understand what you're asking now I think. If you want to execute something in a file from the shell, the easiest way is to encapsulate it in a Class.
Try changing your code to the following:
#!/usr/bin/python
class Hello:
def __init__(self):
print "Hello, Interactive Shell World!"
raw_input()
This makes a class called Hello where the constructor function runs the code you have in your current file. Then, start an interactive shell started in the same directory as the hello.py file. Here is a paste from an example session:
>>> from hello import Hello
>>> Hello()
Hello, Interactive Shell World!
<hello.Hello instance at 0xb782686c>
>>>
It prints the message, waits for input, then prints the string representation of the newly created object and returns to the prompt. If you want to avoid the last printout just assign the object to a variable like:
>>> h = Hello()
If you want to keep the ability to execute the file from the command line (rather than the shell) add this code to the bottom of the file:
if __name__ == '__main__':
Hello()
You do "chmod +x" from the terminal. In the directory of the hello.py, run:
chmod +x hello.py
This gives you the ability to run your file like ./hello.py instead of "python hello.py". Now that I think of it, it sounds like you may be confusing the python interactive shell which a unix shell. You can run your file easily using "python hello.py" from a unix shell, but to run code from the python interactive shell, you will want to do something like I did above.

To configure PyDev, make sure you read its getting started manual: http://pydev.org/manual_101_root.html
Now, probably you're having a syntax error because you're using Python 3, where print is no longer a keyword, but a function (so, you have to use print() as a function call), and also have in mind that raw_input() was renamed to input() on Python 3).

To answer your first question to import into interactive mode just use import filename but don't include the .py
C:\Users\CodeThis\Documents\py\search>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.
>>> import aStar
>>> aStar.search((0,0),(5,9))
[(0, 0), (9, 0), (8, 0), (7, 0), (6, 0), (6, 9), (5, 9)]
>>>
something like that anyway

Related

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

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

Import numpy from macOS Terminal running python launches but not from python script

My goal is to be able to run NumPy through simple scripts. Being new at this, simple is not so simple. From the Terminal running python, NumPy works just fine. However, I can not import it from a script. The numpy sample runs from python with the following result.
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
However, from my script, runNumPy.py
#!/usr/bin/sh/env python3.6
print("Hello world! from runNumPy.py in python called by Terminal")
import sys, os
print("Current Working Directory: ", os.getcwd())
import numpy as np
I get
>>> a = np.arange(15).reshape(3, 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'np' is not defined
I have tried it with "import numpy as np" and without "as np."
My Terminal script is
#!/bin/sh
echo "Hello, world! Starts helloWorld.sh Terminal script."
source opt/anaconda3/etc/profile.d/conda.sh
conda activate bioETE
cd opt; cd anaconda3; cd envs; cd bioETE; cd lib; cd python3.6; cd site-packages
python ./runNumPyS.py #This runs runNumPyS.py from the terminal
python ./runNumPy.py #This runs the runNumPy.py from the terminal
python
It's output is
Hello, world! Starts helloWorld.sh Terminal script.
Hello world: from helloWorld.py in python script called by Terminal
Hello world! from runNumPy.py in python called by Terminal
Current Working Directory: home/opt/anaconda3/envs/bioETE/lib/python3.6/site-packages
Python 3.6.12 |Anaconda, Inc.| (default, Sep 8 2020, 17:50:39)
[GCC Clang 10.0.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
As stated before my goal is to begin NumPy at the python prompt >>> without using another import statement. This shell script works fine. It calls the python scripts.
In the output above, the first "Hello World" was to show the shell script was working before I went any further. The other two, "Hello World", were to see if the python scripts were called.
You can see by th python script output the python print commands and sys and os import calls worked OK. The system call seems to tell me I am in the correct directory..??
The runNumPy.py script is
#!/usr/bin/sh/env python3.6
print("Hello world! from runNumPy.py in python called by Terminal")
import sys, os
print("Current Working Directory: ", os.getcwd())
import numpy as np
At the python prompt, I get the following error.
>>> a = np.arange(15).reshape(3, 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'np' is not defined
Clearly, numpy has not been imported. Again, at this same prompt, if I type in the "import numpy as np" first, NumPy works just fine.
NumPy's module numpy is located at
home/opt/anaconda3/envs/bioETE/lib/python3.6/site-packages/numpy
I've tried placing python script, runNumPy.py, in two places.
1)home/opt/anaconda3/envs/bioETE/lib/python3.6/site-packages
2)home/opt/anaconda3/envs/bioETE/lib/python3.6/
Neither place seems to work. I'm stuck for the moment. Any and all helpful suggestions or a solution or two will be appreciated.
You write:
As stated before my goal is to begin NumPy at the python prompt >>> without using another import statement. This shell script works fine. It calls the python scripts.
This is actually not a good goal. You should try to get out of the habit of running python from the interactive prompt. It's hard to develop significant programs that way. If you really want to run Python this way, you should look into use Jupyter Notebook or JupyterLab, both of which are included in your Python anaconda release.
The reason you don't want to just hack a bunch of stuff into your environment is that you won't be able to create scripts or programs that others can easily use. This is also the reason that you don't want to build a dependency on your current directory into your program. You should rely on site-packages being in sys.path; you should not be changing your current directory so that site-packages is your current directory.
Does this make sense?
However, if you really want to muck with the command line environment, you will find it useful to read this document:
https://docs.python.org/3/using/cmdline.html
In particular, set the environment variable PYTHONSTARTUP to contain the python commands that you want executed before python starts up in interactive mode.

How to avoid restarting python shell after each import

When I run the terminal then access to python3 shell, I can run a file or module using import, but if I try to run it again, nothing happens.
I saw this question before: [Need to restart python in Terminal every time a change is made to script
and I read the docs: [https://docs.python.org/3/tutorial/modules.html#executing-modules-as-scripts][1]
but both are talking about restarting a single function in the module. I am talking about rerunning the whole file.
I included this code in the end of my file, but still nothing happened
if __name__ == "__main__":
pass
UPDATE:
After I ran the file as in the comments, this is what I got:
Ms-MBP:mine M$ python3
Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> python python_file.py
File "<stdin>", line 1
python python_file.py
^
SyntaxError: invalid syntax
>>>
As mentioned in the comments, if you're working in a terminal you should use the command (remember to do this from the main shell, ie probably bash, not from the Python shell)
$ python script.py
This is the intended way to execute python files. You can normally quickly cycle back to the previous command with the UP arrow on your keyboard.
However, if you for some reason really need to run your script from the interactive interpreter, there are some options, although beware that they are kind of hacky and probably not the best way to go about running your code, although this may vary with what your specific use case is.
If your script, hello.py, had the following source:
print("hello world")
In python3 you could do the following from the shell:
>>> from importlib import reload
>>> import hello
hello world
>>> reload(hello)
hello world
<module 'hello' from '/home/izaak/programmeren/stackoverflow/replrun/hello.py'>
Here is the documentation for importlib.reload. As you can see, this replicates the side effects of the script. The second part is the repr() of the module, as the reload() function returns the module - this is nothing to worry about, it is part of the way the interpreter works, in that it prints the value of anything you enter into it - eg you can do
>>> 2 + 3
5
rather than having to explicitly print(2 + 3). If this really bother you, you could do
>>> from importlib import reload as _reload
>>> def reload(mod):
... _reload(mod)
...
>>> import hello
hello world
>>> reload(hello)
hello world
However, it would be more idiomatic for your script to look something like this, using that if statement you found (this was also a suggestion in the comments):
def main():
print("hello world")
if __name__ == "__main__":
main()
This way, from the Python shell you can do:
>>> import hello
>>> hello.main()
hello world
>>> hello.main()
hello world
This is very good practice. The if statement here checks if the script is being executed as the 'main' script (like running it directly from the command line, as in my first suggestion), and if so it executes the main function. This means that the script will not do anything if another script wants to import it, allowing it to act more like a module.
If you're using IPython, you'll probably know this but this becomes a lot easier and you can do
In [1]: %run hello.py
hello world

Can't run Python code in Command Prompt

I'm new to Python and I created my first piece of code which is simply
print('Hello World!')
and it works fine and I named it hello.py. When I try to open the file it says with "python hello.py"
I get an error message that says
File "hello.py", line 1
PYthon 3.4.4 (v3.3.3:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1.600 64 bit (AMD65)] on win32
SyntaxError: invalid syntax
I added Python to the PATH so I don't know what's the issue
You're not supposed to put those lines into your script. They come from the interpreter, giving information to you. You're only supposed to include in your script the commands that you want to give to the interpreter. In your case, your hello.py file should consist entirely of this:
print('Hello World!')
and nothing else.

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