Invalid Python Syntax Error - python

Inside the shell, I get the following response when I try to import my program.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tweet.py", line 26
print "Favorited: %s" % (result['text'])
^
SyntaxError: invalid syntax
Why does print "Favorited: %s" % (result['text']) return an error? Googling has been unhelpful, this was working for me earlier...
Update, I'm running the following version of Python:
Python 2.7.5 |Anaconda 1.6.1 (x86_64)| (default, Jun 28 2013, 22:20:13)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Update again, here is the function:
def fetch_tweet(tweet):
try:
result = t.favorites.create(_id=tweet['id'])
print "Favorited: %s" % (result['text'])
return result
# when you have already favourited a tweet, this error is thrown
except TwitterHTTPError as e:
print "Error: ", e
return None
Update #3 - found the error!
Turns out my python interpreter really hated a bit of code I had at the top, which was messing with print somehow - I deleted from __future__ import print_function from the top of the file and everything started working smoothly.

I see you got it working, but here's the explanation:
Python 3 changed how printing works for various reasons. The big change is that print is now a function instead of a statement (this is helpful because it allows you to, say, pass parameters to it if you want to change things like where it prints to, whether to terminate with a newline, etc)
So when you had the line:
from __future__ import print_function
It was using Python 3 printing, but you're running in Python 2. One solution (as you found) is to remove the import, but you could also change the print statement to a function. For simple statements like this you just need to add parens, so this would have worked:
print("Favorited: %s" % (result['text']))
These would also work:
print("Favorited: {}".format(result['text']))
print("Favorited:", result['text'])

Related

Python 'raise' without arguments: what is "the last exception that was active in the current scope"?

Python's documentation says:
If no expressions are present, raise re-raises the last exception that was active in the current scope.
(Python 3: https://docs.python.org/3/reference/simple_stmts.html#raise; Python 2.7: https://docs.python.org/2.7/reference/simple_stmts.html#raise.)
However, the notion of "last active" seems to have changed. Witness the following code sample:
#
from __future__ import print_function
import sys
print('Python version =', sys.version)
try:
raise Exception('EXPECTED')
except:
try:
raise Exception('UNEXPECTED')
except:
pass
raise # re-raises UNEXPECTED for Python 2, and re-raises EXPECTED for Python 3
which results in something I didn't expect with Python 2:
Python version = 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
Traceback (most recent call last):
File "./x", line 10, in <module>
raise Exception('UNEXPECTED')
Exception: UNEXPECTED
but has the expected (by me) result with Python 3:
Python version = 3.6.8 (default, Feb 14 2019, 22:09:48)
[GCC 7.4.0]
Traceback (most recent call last):
File "./x", line 7, in <module>
raise Exception('EXPECTED')
Exception: EXPECTED
and
Python version = 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)]
Traceback (most recent call last):
File "./x", line 7, in <module>
raise Exception('EXPECTED')
Exception: EXPECTED
So what does "the last ... active" mean? Is there some documentation on this breaking change? Or is this a Python 2 bug?
And more importantly: What is the best way to make this work in Python 2? (Preferably such that the code will keep working in Python 3.)
Note that if one changes the code to
#
from __future__ import print_function
import sys
print('Python version =', sys.version)
def f():
try:
raise Exception('UNEXPECTED')
except:
pass
try:
raise Exception('EXPECTED')
except:
f()
raise # always raises EXPECTED
then things start to work for Python 2 as well:
Python version = 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
Traceback (most recent call last):
File "./x", line 13, in <module>
raise Exception('EXPECTED')
Exception: EXPECTED
I'm considering to switch to that...
The Python 2 behavior is not so much a bug as a design flaw. It was addressed in Python 3.0 by adding the exception chaining features. The closest thing to documentation of this change can be found in PEP 3134 -- Exception Chaining and Embedded Tracebacks
motivation:
During the handling of one exception (exception A), it is possible that another exception (exception B) may occur. In today's Python (version 2.4), if this happens, exception B is propagated outward and exception A is lost.
This is exactly what you're seeing in 2.7: EXPECTED (A) was lost because UNEXPECTED (B) appeared and overwrote it. With the newer exception chaining features in Python 3, the full context of both errors can be preserved via __cause__ and __context__ attributes on exception instances.
For a more direct cross-compatible workaround, I would encourage you to keep the references manually, explicitly show which error is being re-raised, and as usual avoid bare except statements (which are always too broad):
try:
raise Exception('EXPECTED')
except Exception as err_expected:
try:
raise Exception('UNEXPECTED')
except Exception as err_unexpected:
pass
raise err_expected
Should you wish to suppress the exception-chaining feature in a cross-compatible way, you can do that by setting err_expected.__cause__ = None before re-raising.
raise uses the same information as sys.exc_info, which documents both behaviors. Since the per-frame behavior that your workaround exploits is documented, that’s the way to go.
PEP 3110 made several changes to the except statement. I believe it included this one, but the only thing explicitly mentioned is that an exception stored by as is discarded when leaving the except.

BadOptionError when import volatility.conf

I write below code and it gives me error in first line! whats wrong is with this code:
import volatility.conf as conf
import volatility.registry as reg
import volatility.commands as commands
import volatility.addrspace as addrspace
import volatility.plugins.taskmods as taskmode
# configure volatility
reg.PluginImporter()
config=conf.ConfObject()
reg.register_global_options(conf,commands.Command)
reg.register_global_options(conf,addrspace.BaseAddressSpace)
config.parse_options()
config.PROFILE="Linuxfedora32x64"
config.LOCATION="./dumps/mem.lime"
p=taskmode.PSList(config)
for process in p.calculate:
print(process)
the error code:i think there is some code insode conf.py witch in not support in python 3.6 .but volatility is copatible with python 3.6. so i don't know what to do :
Traceback (most recent call last):
File "../PycharmProjects/volpractive/test.py", line 6, in <module>
import volatility.conf as conf
File "/anaconda3/lib/python3.6/site-packages/volatility-2.6-py3.6.egg/volatility/conf.py", line 84
except (optparse.BadOptionError, optparse.OptionValueError), err:
You were right, the line:
except (optparse.BadOptionError, optparse.OptionValueError), err:
is not Python3 compatible (according to [Python]: The try statement).
According to [GitHub]: volatilityfoundation/volatility - (2.6) volatility/README.txt:126+ (as it is at this point):
Requirements
============
- Python 2.6 or later, but not 3.0. http://www.python.org
Note:
The stacktrace is still incomplete (missing the last line - should be SyntaxError); that would have cleared things up much sooner
So, you have to run it with Python2.6+ (of course you could also modify the code (at least the part that you need) to be Python3 compatible, but I doubt that's feasible).

Qt - How to write "more" data to QProcess?

I am facing an issue I faced a few times so far.
The issue in question just gets solved by itself every time, without me understanding what is causing it
So what happens is that I start a python virtual environment from my c++ code. That works, afterwards by using the write function I am able to write stuff in that environment. This also works perfectly fine so far. However I am unable to write my last command to the process.
I though about maybe some buffer being full but I didn't really find anything about a buffer in the Qt docs
This is the relevant piece of code:
static QStringList params;
QProcess *p = new QProcess();
params<<"-f"<<"-c"<<"python2"<< "/home/John/Desktop/python.log";
qDebug()<<"parameters: "<<params;
qDebug()<<"going to write";
p->start("script", params);
qDebug()<<"Turning on new user process...";
while(!p->waitForStarted())
{qDebug()<<"waiting for virtualenv to be ready";}
successFailWrite = p->write("import imp;\n");
while(!p->waitForBytesWritten());
successFailWrite = p->write("foo = imp.load_source('myTest', '/home/John/recognitionClass.py');\n");
while(!p->waitForBytesWritten());
successFailWrite = p->write("from myTest import recognitionClass;\n");
while(!p->waitForBytesWritten());
successFailWrite = p->write("myClassObj = recognitionClass();\n");
if(successFailWrite !=-1)
{qDebug()<<"OK written";}
while(!p->waitForBytesWritten());
successFailWrite = p->write("habelahabela\n");
if(successFailWrite !=-1)
{qDebug()<<"OK written";}
QString name = "John";
QString processNewUserParameter= "print myClassObj.addNewUser("+ name +");\n";
QByteArray processNewUserParameterByteArr= processNewUserParameter.toUtf8();
p->write(processNewUserParameterByteArr);
I keep a log file which contains what is being written to the python virtualenv and what is being printed
Script started on Son 27 Aug 2017 20:09:52 CEST
import imp;
foo = imp.load_source('myTest', '/home/John/recognitionClass.py');
from myTest import recognitionClass;
myClassObj = recognitionClass();
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import imp;
>>> foo = imp.load_source('myTest', '/home/John/recognit
<myTest', '/home/John/recogniti onClass.py');
/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
/usr/local/lib/python2.7/dist-packages/sklearn/grid_search.py:43: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.
DeprecationWarning)
>>> from myTest import recognitionClass;
>>> myClassObj = recognitionClass();
>>>
It does pront "OK written" twice, which on one side proves that I successfully wrote my commands to the process, yet I can't see anything.
As you can see the test sentence "habelahabela" doesn't get written neither.
Does anybody have an idea about what I may be doing wrong?
I know that I am writing my commands to quickly to the environment. Because as you can see I start by writing "import imp", it then gets buffered and a little later the buffer gets flushed and the virtualenv executes the command (this is why you see it twice).
Does anybody see why I can't see the test-sentence and -more importantly- my actual command "print myClassObj.addNewUser("+ name +");\n" being printed to the virtual environment?
Thanks
First of all, there is no sense in writing while(!p->waitForBytesWritten());. waitForBytesWritten already blocks your thread without a while loop and, as the name states, waits until bytes are written. It returns false only if there are either timeout or an error. In the first case you should give it more time to write bytes. In the second case you should fix the error and only then try again.
The same holds for waitForStarted and all other Qt functions starting with "waitFor...".
So the usage looks like:
if(!p->waitForBytesWritten(-1)) // waits forever until bytes ARE written
{
qDebug() << "Error while writing bytes";
}
Regarding the question: I believe the problem (or at least a part of it) is that you write your last 2 messages into p, but you neither wait for bytesWritten() signal, nor use waitForBytesWritten() blocking function. Although, there is probably no error occuring (because p->write(...) does not return -1 at that point), however it does not mean that your message is written yet. In a nutshell, wait for bytesWritten() signal...
QProcess inherits from QIODevice, so I recommend to look its docs and learn about it a bit more.

Is it possible to remove a method from a module?

Can I remove a method from a ready module in python? Recently i was trying to write a python code in a browser based trading platform where in they allow usto import python 'time' package but the time package didn't have sleep() method. While i was trying to import sleep method it gave me attribute error. On asking the technical support people of that platform i got to know that they don't support sleep() method. I am just wondering how could we do that? is it just deleting the method from the package? Or are there any better ways?
It is possible to remove methods (functions) from a name space at run time.
This is called monkey patching. Example in an interactive session:
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 time
>>> time.sleep(2)
>>> del time.sleep
>>> time.sleep(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'sleep'
But back to your original question: I believe that on the platform you are using they might have replaced several standard library modules (including the time module) with customized versions. So you should ask them how you can achieve the delay you want without having to resort to busy waiting.
import time
time.sleep(1)
del time.sleep
time.sleep(1)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-07a34f5b1e42> in <module>()
----> 1 time.sleep(1)
AttributeError: 'module' object has no attribute 'sleep'
If you don't have the time.sleep method, you can easily write your own (albeit not likely as precise or efficient):
def sleep(seconds):
a = time.time()
b = time.time()
while b - a < seconds:
b = time.time()
Here are some tests for precision that I ran (only a print statement to see how often it went into the loop):
>>> sleep(1)
2.86102294922e-06
0.0944359302521
0.14835691452
0.198939800262
0.249089956284
0.299441814423
0.349442958832
0.398970842361
0.449244022369
0.498914003372
0.549893856049
0.600338935852
0.648976802826
0.700131893158
0.750012874603
0.800500869751
0.850263834
0.900727987289
0.950336933136
1.00087189674
The precision stays at 100th mile seconds precision. :)
You might not have the method either because they modified the source code, or ran some things on the interpreter before your code began executed (using the del keyword like in the other answers).

Beginner of Python: <Syntaxerror: invalid syntax> when trying to import program

This is my first day learning programming. I'm following Python Programming: An introduction to computer science 2nd ed. by John Zelle, and so far things have been going smoothly.
The only trouble is that when I try and import a saved program I get a syntaxerror. I write the program and save it before executing, but then when I try to import it I get the error. I tried opening a fresh instance of the shell but no cigar. I'm using OSX Lion 10.8 and Python 2.7.3. Any help is appreciated. This is what the problem looks like:
>>> #File: chaos.py
>>> #A simple program illustrating chaotic behavior.
>>> def main():
print "This program illustrates a chaotic function"
x=input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1-x)
print x
>>> main()
This program illustrates a chaotic function
Enter a number between 0 and 1: .25
0.73125
0.76644140625
0.698135010439
0.82189581879
0.570894019197
0.955398748364
0.166186721954
0.540417912062
0.9686289303
0.118509010176
>>> import chaos
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
import chaos
File "chaos.py", line 1
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
^
SyntaxError: invalid syntax
My guess is that you are copying the contents of the terminal to the file, verbatim. And there are a lot of thing that should not be there, that includes the version prompt.
The file should have just something like:
#File: chaos.py
#A simple program illustrating chaotic behavior.
def main():
print "This program illustrates a chaotic function"
x=input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1-x)
print x
No >>>, no ..., no tabulators and certainly do not copy the version information:
Python 2.7.3 (default, Dec 22 2012, 21:27:36)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
File "chaos.py", line 1
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
^
SyntaxError: invalid syntax
It looks like the first line of your chaos.py script has a line which is not python:
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
It should be removed or commented-out by starting the line with a # sign.
Some tips to keep in mind:
In Python, whitespace is important -- they indicate indentation
level. Do not mix spaces and tabs lest Python raise IndentationErrors.
In texts or web pages, you may see transcripts of interactive
sessions which include >>> or ... indicating the Python prompt or
indentation level. If you transfer the code to a script, you must
remove those.

Categories