python idle 2.7.9 gives a false syntax error - python

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

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.

Pycharm - using pwntools with remote interpreter on WSL

I am using remote interpreter on pycharm on WSL (configured it with this tutorial: https://www.jetbrains.com/help/pycharm/using-wsl-as-a-remote-interpreter.html)
I was able to run everything I needed successfully, but when I tried to use pwntools (https://github.com/Gallopsled/pwntools) I was able to import it successfully on the WSL bash python interpreter, but not on Pycharm.
This is what I ran:
from pwn import *
On Pycharm it was stucked and I interrupted it, this is the trace of the Exception (where it stucks):
ssh://shahar#localhost:22/usr/bin/python -u /tmp/pycharm_project_271/pwnablekr/fd.py
Traceback (most recent call last):
File "/tmp/pycharm_project_271/pwnablekr/fd.py", line 1, in <module>
from pwn import *
File "/home/shahar/.local/lib/python2.7/site-packages/pwn/__init__.py", line 6, in <module>
pwnlib.args.initialize()
File "/home/shahar/.local/lib/python2.7/site-packages/pwnlib/args.py", line 208, in initialize
term.init()
File "/home/shahar/.local/lib/python2.7/site-packages/pwnlib/term/__init__.py", line 74, in init
term.init()
File "/home/shahar/.local/lib/python2.7/site-packages/pwnlib/term/term.py", line 109, in init
c = os.read(fd.fileno(), 1)
KeyboardInterrupt
Process finished with exit code 1
enter code here
On my WSL bash it ran just fine:
shahar#MYCOMPUTERNAME:/mnt/c/Users/shahar$ python
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pwn import *
>>>
When I looked at the piece of code where it stuck (from the trace of the Exception):
while True:
c = os.read(fd.fileno(), 1)
s += c
if c == 'R':
break
at the beginning of the script as a global variable:
fd = sys.stdout
I understood from the internet that this function (which this loop is part of it) is related to take over the terminal. Maybe it is related to the fact I am not running from terminal?
Had anyone seen this kind of problem before? has some helpful tips?
Thank you very much!
I have a potential fix as well, and it's adding a PWNLIB_NOTERM to the environment.
import os
os.environ['PWNLIB_NOTERM'] = 'True' # Configuration patch to allow pwntools to be run inside of an IDE
import pwn
Screenshot showing it runs and we get an Encoder object instance
There is another way to solve it.
If you use Pycharm , you can tick the box Run with Python console in Run configurations.
It will work in Pycharm 2020.3 with IPython.(I think it also works without IPython)
screenshot
There is no effective way, I debug it, the problem is term initialization.it may also be related to the environment variables of the TERM and TERMINFO.My solution is to modify the last line of /usr/local/lib/python2.7/dist-packages/pwnlib/args.py,delete term.init(), replace it with anything else to bypass the initialization of pwnlib.
replace this line:
debug pwntools:

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 import the cx_Oracle module unless I'm using an interactive shell

When using Python on an interactive shell I'm able to import the cx_Oracle file with no problem. Ex:
me#server~/ $ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_Oracle
>>>
As you can see, importing works without a hitch. However, when I try to run a Python script doing the same thing, I get an error:
me#server~/ $ sudo script.py
Traceback (most recent call last):
File "/usr/local/bin/script.py", line 19, in <module>
import cx_Oracle
ImportError: No module named "cx_Oracle'
Here is the important section from script.py:
# 16 other lines above here
# Imports
import sys
import cx_Oracle
import psycopg2
...
I'm befuddled here. Other pertinent information is the server I'm running is Ubuntu 14.04.1 LTS (upgraded from 12.04) 64bit. which python and sudo which python both point to the same location. Also, doing this as root via sudo su - gets the same results; import OK from interactive but error from script.
Nothing other than the OS upgrade happened between when this worked and when it stopped working.
Sorry, all. This was a silly on my part. Turns out the script in question was using Python3, and when the server upgraded, Python3 went from being 3.2 version to being 3.4 version.
Once the cx_Oracle module was set up in the 3.4 version, everything worked as expected.
Phil, your final note talking about the shebang was what lead me to discover this, so kudos to you! The reason I didn't mark your response as the answer was because technically it wasn't but led me on the right path.
Cheers!
sudo starts a new bash environment which is then pointing to a different python executable (different installed modules).
You can verify this with which python and sudo which python
EDIT: so if they point to the same executable, then you should look at sys.path to find differences. In both environemnts you can:
python -c "import sys; print('\n'.join(sys.path))"
sudo python -c "import sys; print('\n'.join(sys.path))"
Look for differences. If there are none:
A common error in import situations like this is that python will first look at the local dir. So if you happen to be running python and importing something what is found locally (i.e. cx_Oracle is a subdir of your current location), you will get an import error if you change directories.
Final note: I have assumed here that the shbang of the script.py points to the same executable as which python. That is, that python script.py and script.py return the same error.

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

Categories