open function not returning file descriptor - python

Python open function does not return file descriptor. Why could this be? I am using python 3.3.
test_file_open.py
#!/usr/bin/env python
import sys
if __name__ == '__main__':
html = ""
hmtl_fd = open("ns_temp.html",'r')
for line in html_fd:
html += line
Output:
Traceback (most recent call last):
File "./test_file_open.py", line 7, in <module>
for line in html_fd:
NameError: name 'html_fd' is not defined
Permissions:
-rwxr-xr-x 1 michael michael 160 Mar 16 23:03 test_file_open.py

There is a typo in a variable name, see hmtl_fd and html_fd.
Replace:
hmtl_fd = open("ns_temp.html",'r')
with:
html_fd = open("ns_temp.html",'r')

Typo: hmtl_fd in place of html_fd

Related

how to export WBlock by using pyautocad

hi all i have this problem when i try to export object through WBlock what is wrong there i'm try to do simple python work (note: i'm beginners :D) .. any help
from pyautocad import Autocad, APoint,utils
import win32com.client
AutoCAD = win32com.client.dynamic.Dispatch("AutoCAD.Application")
acad = Autocad(create_if_not_exists = False)
acad.Visible=True
doc = AutoCAD.ActiveDocument
layersList = doc.Layers
for l in layersList:
object = acad.iter_objects()
if l.name == "0":
pass
else:
for o in object:
if o.ObjectName == "AcDbText":
SelectionSet = doc.SelectionSets.Item(o.ObjectName).Name
directoryN = "C:\\Temp\\{}_{}.dwg".format(l.name,o.TextString)
doc.WBlock(directoryN,SelectionSet)
here what i Get
AcDbText
Traceback (most recent call last):
File "C:/Temp/Exporter.py", line 23, in <module>
doc.WBlock(directoryN,SelectionSet)
File "<COMObject <unknown>>", line 2, in WBlock
pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 2)
thanks
i'm try to export every text as WBlock

How can I fix my module system for my coding language?

I am making a coding language with Python. I am working on a module system for custom made modules.
The full code is at https://repl.it/#UCYT5040/koolCode and interp.py but the issue I am having is with this code:
for i in keywords:
keyword = i.lower()
if keyword == "print":
for i1 in quotes:
print(i1)
elif keyword == "add":
for i1 in quotes:
quote = i1.lower()
if quote == "python":
modulesInfo["python"] = {"runLang":"python","runpy":"{quote}"}
modules.append("python")
else:
print("koolCode WARN: custom modules not supported/module not found.")
else:
for i1 in modules:
if modulesInfo[i1]["runLang"] == "python":
try:
eval("f\"" + modulesInfo[i1][keyword] + "\"")
except KeyError:
print(f"koolCode ERROR: Module")
I get this error:
Welcome to koolCode console.
Would you like to open a file? y/n
n
A file will not be opened. Type any commands below.
koolCode>add "python"
['add'] ['python']
koolCode>runpy "help()"
Traceback (most recent call last):
File "main.py", line 8, in <module>
noFile()
File "main.py", line 3, in noFile
runString(input("koolCode>"))
File "/home/runner/koolCode/interp.py", line 46, in runString
eval("f\"" + modulesInfo[i1][keyword] + "\"")
File "<string>", line 1, in <module>
NameError: name 'quote' is not defined
How can I do this?

Javascript grammar in antlr4 and python

I have used the following link for JavaScript grammar .
https://github.com/antlr/grammars-v4/tree/master/javascript/javascript/Python
i have used antlr4.8 and ntlr4-python3-runtime==4.8. when i use the following code it gives following error .
error:
PS N:\antlr4\sample\py4.8> python main.py test.js
Running
Test started for: test.js
Created parsers
Traceback (most recent call last):
File "main.py", line 25, in <module>
main(sys.argv)
File "main.py", line 20, in main
tree = parser.program()
File "N:\antlr4\sample\py4.8\JavaScriptParser.py", line 880, in program
self.enterRule(localctx, 0, self.RULE_program)
File "C:\Users\root\AppData\Local\Programs\Python\Python38\lib\site-packages\antlr4\Parser.py", line 366, in enterRule
self._ctx.start = self._input.LT(1)
.
.
.
File "N:\antlr4\sample\py4.8\JavaScriptLexer.py", line 919, in sempred
return pred(localctx, predIndex)
File "N:\antlr4\sample\py4.8\JavaScriptLexer.py", line 925, in HashBangLine_sempred
return this.IsStartOfFile()
NameError: name 'this' is not defined
code:
import sys
from antlr4 import *
import JavaScriptLexer
import JavaScriptParser
JSL = JavaScriptLexer.JavaScriptLexer
JSP = JavaScriptParser.JavaScriptParser
class WriteTreeListener(ParseTreeListener):
def visitTerminal(self, node:TerminalNode):
print ("Visit Terminal: " + str(node) + " - " + repr(node))
def main(argv):
input_stream = FileStream(argv[1])
print("Test started for: " + argv[1])
lexer = JSL(input_stream)
stream = CommonTokenStream(lexer)
parser = JSP(stream)
print("Created parsers")
tree = parser.program()
ParseTreeWalker.DEFAULT.walk(WriteTreeListener(), tree)
if __name__ == '__main__':
print("Running")
main(sys.argv)
print("Hello")
What have I done wrong ?
Replace this with self
(ref here). Example:
Change
return this.IsStartOfFile()
to
return self.IsStartOfFile().
Run the script transformGrammar.py, as indicated in documentation.

Is there a bug in this python module or am I using it the wrong way?

lambda from getattr getting called with "connection" as a keyword argument? Am I misusing the code or is there a bug?
Code and traceback: https://github.com/bigcommerce/bigcommerce-api-python/issues/32
#!/usr/bin/env python2
import bigcommerce
import bigcommerce.api
BIG_URL = 'store-45eg5.mybigcommerce.com'
BIG_USER = 'henry'
BIG_KEY = '10f0f4f371f7953c4d7d7809b62463281f15c829'
api = bigcommerce.api.BigcommerceApi(host=BIG_URL, basic_auth=(BIG_USER, BIG_KEY))
def get_category_id(name):
get_request = api.Categories.get(name)
try:
cat_list = api.Categories.all(name=name)
if cat_list:
return cat_list[0]['id']
else:
return None
except:
return None
def create_category(name):
rp = api.Categories.create(name)
if rp.status == 201:
return rp.json()['id']
else:
return get_category_id(name)
create_category('anothertestingcat')
Gives this traceback:
Traceback (most recent call last):
File "./bigcommerceimporter.py", line 50, in
create_category('anothertestingcat')
File "./bigcommerceimporter.py", line 44, in create_category
rp = api.Categories.create(name)
File "/home/henry/big_test_zone/local/lib/python2.7/site-packages/bigcommerce/api.py", line 57, in
return lambda args, *kwargs: (getattr(self.resource_class, item))(args, connection=self.connection, *kwargs)
TypeError: create() got multiple values for keyword argument 'connection'
Line in api.py that the traceback refers to: https://github.com/bigcommerce/bigcommerce-api-python/blob/master/bigcommerce/api.py#L57
According to the examples, create should be used like this:
api.Categories.create(name = 'anothertestingcat')
Note: You should generate a new API KEY, since you published the current one in this question.

Implementing C-like assert

I'm trying to implement an assert function. How can I get the text of the failing condition into the error message? If I have to parse it from the backtrace, can I portably rely on anything about the format of frames?
AssertionError is just like any other exception in python, and assert is a simple statement that is equivalent to
if __debug__:
if not expression: raise AssertionError
or
if __debug__:
if not expression1: raise AssertionError(expression2)
so you can add a second parameter to your assertion to have additional output
from sys import exc_info
from traceback import print_exception
# assertions are simply exceptions in Python
try:
assert False, "assert was false"
except AssertionError:
print_exception(*exc_info())
outputs
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
AssertionError: assert was false
If you're sure the expression to test is secure you could do something like this:
File my_assert.py:
import sys
def my_assert(condition):
caller = sys._getframe(1)
if not eval(condition, caller.f_globals, caller.f_locals):
raise AssertionError(repr(condition) + " on line " +
str(caller.f_lineno) + ' in ' +
caller.f_code.co_name)
File test_my_assert.py:
from my_assert import my_assert
global_var = 42
def test():
local_var = 17
my_assert('local_var*2 < global_var') # OK
my_assert('local_var > global_var')
test()
Output:
Traceback (most recent call last):
File "test_my_assert.py", line 10, in <module>
test()
File "test_my_assert.py", line 8, in test
my_assert('local_var > global_var')
File "my_assert.py", line 8, in my_assert
caller.f_code.co_name)
AssertionError: 'local_var > global_var' on line 8 in test
My very hackish solution:
def my_assert(condition):
if not eval(condition):
# error stuff
Then use it by placing the condition in quotation marks. It is then a string that can be printed in the error message.
Or, if you want it to actually raise an AssertionError:
def my_assert(condition):
if not eval(condition):
raise AssertionError(condition)

Categories

Resources