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
Related
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
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.
I have a file: pytest.py which is one line:
print "hello world"
idle -r pytest.py
Python 2.7.9 (default, Apr 8 2015, 15:12:41)
[GCC 4.2.1 Compatible FreeBSD Clang 3.4.1 (tags/RELEASE_34/dot1-final 208032)] on freebsd10
Type "copyright", "credits" or "license()" for more information.
>>>
*** Error in script or command!
Traceback (most recent call last):
File "pytest.py", line 1
print "hello world"
^
SyntaxError: invalid syntax
>>>
running idle with no options, opening and running the file works. This is on FreeBSD 10.0 and py27-gtk2-2.24.0_3 (python binding). This stopped working at some point but I can not relate it to a specific change. All packages/port are up-to-date
Idle compiles the -r code as follows:
code = compile(source, filename, "exec")
However, by default, compile inherits the calling code's future settings:
The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile()
Since idle's PyShell.py module does enable the print_function future flags, this means that by accident all of your code in -r has to use it to.
Change your code to print("Hello world") to fix the problem. As a nice side effect, your code will work in Python 3.x as well.
I caused this problem when I added
from __future__ import print_function
to the top of PyShell.py as part of backporting the bugfix in Issue 22420. The fix, which I just applied in Issue 24222, is this change to line 655.
- code = compile(source, filename, "exec")
+ code = compile(source, filename, "exec", dont_inherit=True)
Thanks to 'phihag' for pointing out the problem line.
from future import print_function
print "hello world"
gives the same result on my system
Oh poo can't use vi -- the answer was correct
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
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