Python 3.4 syntax errors from using print function [duplicate] - python

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 6 years ago.
I'm running files obtained from the web in my desktop's Python 3.4 install, and getting syntax errors, such as:
class MyClient(IBCpp.IBClient):
def setup(self):
self.stime=None
self.nextId=0
# self.symbol='STK.AAPL'
# self.symbol='CASH.EUR.USD'
self.symbol='FUT.ES.USD.201506'
self.state='first'
skipping a few defs which aren't pre-requisite, there's:
def orderStatus(self,orderId, status, filled, remaining, avgFillPrice,
permId, parentId, lastFillPrice, clientId, whyHeld):
"""
call back function of IB C++ API which update status or certain order
indicated by orderId
"""
print self.symbol, status, 'filled=',filled, 'remaining=', remaining'
for which the interpreter responds
print self.symbol, status, 'filled=',filled, 'remaining=', remaining
^
SyntaxError: invalid syntax
Is this perhaps due to a difference of 2.7 vs 3.4? I'm not sure what version the source file was created in. Source is from IBridgePy github repo

Check the Python 3 docs.
Python 3 uses () around the print contents - print ('python')

Related

Is there an alternative to waitForFinished method to check if the process is finished? [duplicate]

This question already has answers here:
Using QProcess.finished() in Python 3 and PyQt
(1 answer)
Qt No such slot for the QProcess::finished() signal
(3 answers)
Closed 2 years ago.
I am currently trying to create an app with PyQt5 and the GUI keeps on hanging.
There were a couple of backend exe files that needed to be executed in the app using command prompt and I found out about the fact that waitForFinished blocks the entire GUI.
I tried going searching it everywhere but no luck. I just found that most of the related questions had just one answer which was to use signals instead of waitForFinished(-1). I wanted to learn how to use signals but nowhere could I find a tutorial of any sorts that could help me.
The code is:
process = QProcess()
cd = "babel.exe"
tem = " "
if not file.endswith("mol"):
tem = re.sub('\..*', '.mol', file)
filech = tem
ar = [file, filech, "-rcpb"]
process.start(cd, ar)
process.waitForFinished(-1)
process.kill
Thanks in advance..

Why does "a is b" behave differently on Interactive mode and when it's ran from script? [duplicate]

This question already has an answer here:
What's with the integer cache maintained by the interpreter?
(1 answer)
Closed 8 years ago.
While trying to answer a question about the use of the is keyword, I figured out that this code:
Script:
a = 123456
b = 123456
print a is b # True
Interactive mode:
>>> a = 123456
>>> b = 123456
>>> a is b
False
was giving different outputs on Python Interactive mode and when it was ran from a script.
From this answer:
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.
So, I would expect that a is b returned True only for integers in the range [-5, 256]. But it is only true on Interactive mode, not when it is ran from a script.
Question: Why does a is b behaves differently on Interactive mode and when it's ran from script?
Note: Tested in Python 2.7 and Python 3
The difference is, how constants are handled. In interactive mode, there is no way to say, if a number constant is already there or not. But for compiled code, every constant is internally saved to a table, and duplicates are removed. But this is a implementation detail, and need not be true for every python version.

Unbound Local Error python [duplicate]

This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 9 years ago.
I need help figuring out why I am getting the following error:
Traceback (most recent call last):
File "prawtest3.py", line 25, in <module>
commentMatcher()
File "prawtest3.py", line 13, in commentMatcher
commentCollection.append(comment)
UnboundLocalError: local variable 'commentCollection' referenced before assignment
This is my code. For background information, I am trying to create a reddit bot that compares a persons comments and then pms a user when the person they are monitoring submits a new comment. If you see a problem with the functionality as well, feel free to share your input. I just need to diagnose my code first to get rid of the syntactical errors before worrying about the semantic ones.
import praw
import time
r = praw.Reddit('PRAW related-question monitor by u/testpurposes v 1.0.')
r.login()
user = r.get_redditor('krumpqueen')
commentCollection = []
commentComparison = []
def commentMatcher():
comments = user.get_comments(limit = 4)
for comment in comments:
commentCollection.append(comment)
time.sleep(60)
comments = user.get_comments(limit = 4)
for comment in comments:
commentComparision.append(comment)
if commentCollection[1] != commentComparision[1]:
r.send_message('krumpqueen', 'just made a new comment', 'go check now')
commentCollection = list(commentComparision)
else:
r.send_message('krumpqueen', 'did not made a new comment', 'sorry')
while(True):
commentMatcher()
Your use of commentCollection makes python (incorrectly1) assume that commentCollection is a local (since you have an assignment to it later and no global statement). When you try to append to the local (which hasn't been created yet) python throws the UnboundLocalError.
1Of course, it's not python making an incorrect assumption, That's how the language is designed to work.
You do commentCollection = list(commentComparision) inside of commentMatcher. Because you've done this, Python concludes you have a local name commentCollection.
Your code fails for the same reason that the code
def foo():
bar.append(3)
bar = []
would fail.
To get commentCollection = list(commentComparision) to a) rebind the global name commentCollection, and b) not make it look like this is a local name at all, add global commentCollection as the first line in the definition of commentMatcher.
In serious code, you wouldn't want to manage your state as globals like this, but rather you'd make an object.

segmentation fault in python [duplicate]

This question already has answers here:
What causes a Python segmentation fault?
(8 answers)
Closed 9 years ago.
How can I run the following program in python 2.7.3
import sys
sys.setrecursionlimit(2 ** 20)
def f(x):
if (x==0): return 0
else: return f(x-1)+1
print f(200000)
This code receives segmentation fault in Ubuntu.
The Python interpreter runs out of stack space. Like any other process in the same situation, it is getting killed by the operating system.
You could try increasing the OS stack size limit (ulimit -c).
A better approach might be to rewrite your code so that it does not require recursion this deep (your particular example can be trivially converted into iteration).

Python, ArcObjects, and .AppRef: how to get from IAppROT to IMxDocument?

I am writing an external Python/comtypes script (in PythonWin) that needs to get a reference to the current ArcGIS 10.0 ArcMap session (through the ArcObjects COM). Because the script is outside the application boundary, I am getting the application reference through the AppROT (running object table). The first code snippet below is the main Python driver module. In it is a function GetApp() to grab an application reference from the AppROT. This code works fine and returns IApplication on the singleton AppRef object. Makes sense, and that's what the ArcObjects reference seems to indicate. Now, my main goal is to get to an IMxDocument. In the main loop, I get to an IDocument successfully and can print the title. The next line, though, a Query Interface, throws an error - NameError: name 'esriArcMapUI' is not defined. The error occurs consistently, even after closing PythonWin and reopening (which you always want to try before you conclude that you have a problem). [BTW, the second code snippet is the CType() function for QI, defined in and imported from the SignHelpers.py module.] So, here are my questions:
(1) What COM object is the IDocument on?
(2) How do I get from my IDocument to the intended IMxDocument? Do I need to create a new MxDocument object first? [Sorry. Two questions there.]
(3) If I don't have to create a new object, then how do I do the QI?
I did a lot of ArcObjects work in VB6 quite a few years ago, so explicit QI's and namespaces are putting the screws to me at the moment. Once I can get to an IMxDocument I will be home free. I would appreciate any help anyone can give me with this.
Also, I apologize for the formatting of the code below. I could not figure out how to get Python code to format correctly. Indentation doesn't work, and some of the Python code is interpreted as formatting characters.
=== code: main py module ===
import sys, os
sys.path.append('C:\GISdata\E_drive\AirportData\ATL\Scripts')
import comtypes
from SignHelpers import *
def GetApp(app):
"""Get a hook into the current session of ArcMap; \n\
Execute GetDesktopModules() and GetStandaloneModules() first"""
print "GetApp called" ####
import comtypes.gen.esriFramework as esriFramework
import comtypes.gen.esriArcMapUI as esriArcMapUI
import comtypes.gen.esriCarto as esriCarto
pAppROT = NewObj(esriFramework.AppROT, esriFramework.IAppROT)
iCount = pAppROT.Count
print "appROT count = ", iCount ####
if iCount == 0:
print 'No ArcGIS application currently running. Terminating ...'
return None
for i in range(iCount):
pApp = pAppROT.Item(i) #returns IApplication on AppRef
if pApp.Name == app:
print "Application: ", pApp.Name ####
return pApp
print 'No ArcMap session is running at this time.'
return None
if __name__ == "__main__":
#Wrap needed ArcObjects type libraries (.olb)...
... code omitted ...
GetDesktopModules(dtOLB) #These force comtypes to generate
GetStandaloneModules(saOLB) #the Python wrappers for .olb's
#Connect to ArcMap
pApp = GetApp("ArcMap")
pDoc = pApp.Document #IDocument on current Document object
print pDoc.Title
pMxDoc = CType(pDoc, esriArcMapUI.IMxDocument) #QI to IMxDocument on MxDocument
=== code for CType() ===
def CType(obj, interface):
try:
newobj = obj.QueryInterface(interface)
return newobj
except:
return None
Scoping error (per the comments):
The import comtypes.gen.esriArcMapUI as esriArcMapUI statement needed to define the esriArcMapUI namespace was being run within the GetApp() function, so the namespace was local to the function.

Categories