Is there a possibility to get the ParserATNSimulator Debuggingmessaging in python3 to work?
I tried to get to the core of ANTLR4 for python 3 and messed a bit with the ATN Simulation. There i wonder about the Class Attributes in ParserATNSimulator() for debugging.
class ParserATNSimulator(ATNSimulator):
debug = False
debug_list_atn_decisions = False
dfa_debug = False
retry_debug = False
Checking the code i see that this should print a lot of Information about the decision making in ANTLR4.
if self.debug or self.debug_list_atn_decisions:
print("predictATN decision " + str(dfa.decision) +
" exec LA(1)==" + self.getLookaheadName(input) +
", outerContext=" + outerContext.toString(self.parser))
Unfortunately it Producing no output when i tried to set it True. Other
parts work as expected.
Is there a possibility to get this information?
def main(argv):
istream = FileStream(argv[1])
lexer = ExLexer(istream)
stream = CommonTokenStream(lexer)
parser = ExParser(stream)
parser._interp.debug = True
parser._interp.debug_list_atn_decisions = True
parser._interp.dfa_debug = True
parser._interp.retry_debug = True
parser.stat()
Thanks in advance!
I get it with #kaby76's help to print output.
I edited the variables in the class in the path. .../site-packages/antlr/antlr4-python3-runtime/atn/ParserATNSimulator.py.
Related
I am trying to get further into testing with python and right now I am hard stuck at trying to write a test for the following code:
def get_files(zip_path: Path):
archive = zipfile.ZipFile(os.path.join(os.path.dirname(__file__), '..', zip_path))
python_files = []
for x in archive.filelist:
if x.filename.endswith(".py"):
python_files.append(x)
return python_files
The test I came up with looks like that:
#mock.patch('zipfile.ZipFile')
def test_get_files(mock_zipfile):
mock_zipfile.return_value.filelist.return_value = [zipfile.ZipInfo('py_file.py'), zipfile.ZipInfo('py_file.py'),
zipfile.ZipInfo('any_file.any')]
nodes = get_ast_nodes(Path('/dummy/path/archive.zip'))
assert len(nodes) == 2
But I am not able to get the test to pass nor do I have any idea what is going wrong.
If someone is looking this up, i might also add the answer. This is how I got it to work:
#mock.patch('zipfile.ZipFile')
def test_get_files(mock_zipfile):
mock_zipfile.return_value.filelist = [zipfile.ZipInfo('py_file.py'), zipfile.ZipInfo('py_file.py'),
zipfile.ZipInfo('any_file.any')]
nodes = get_python_files(zipfile.ZipFile("dummy"))
assert len(nodes) == 2
I want to make a twitch token generator for a discord bot, but when i run it, I get the error
sh: 1: title: not found
I think the part of the code that went wrong is
success = 0
fail = 0
created = 0
def count():
while True:
os.system(f'title S = {success}/ F = {fail} / C = {created}')
time.sleep(1)
full source code here
Does anybody have any ideas? Any help would be appreciated
os.system(f'title S = {success}/ F = {fail} / C = {created}')
Why are you trying to execute a string (which is what os.system() does) that you probably should just be printing out? Something like:
print(f'title S = {success}/ F = {fail} / C = {created}')
Your shell is unlikely to respond well to that.
I wrote code that compares browser's version on device and latest existed version of browser.
Here:
import requests
import subprocess
def get_last_version(browser_name):
res = requests.get("https://vergrabber.kingu.pl/vergrabber.json")
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
return last_version[2:-1]
def get_current_version(app_path):
res = subprocess.Popen(
'defaults read /Applications/' + app_path + '/Contents/Info.plist CFBundleShortVersionString',
shell=True, stdout=subprocess.PIPE).stdout
current_version = res.read()
return current_version
def compare_versions(browser_name, app_path):
if get_last_version(browser_name) == get_current_version(app_path):
return True
else:
return False
def main():
get_last_version('Google Chrome')
print get_last_version('Google Chrome')
get_current_version('Google\ Chrome.app')
print get_current_version('Google\ Chrome.app')
print compare_versions('Google Chrome', 'Google\ Chrome.app')
main()
Here output:
80.0.3987.149
80.0.3987.149
False
I checked len and found that the it is not the same:
80.0.3987.149
13
80.0.3987.149
14
False
Before editing I had following value:
u'80.0.3987.149'
16
80.0.3987.149
14
False
I don't understand why I receive false???
Can you tell me what the problem?
what if you change compare_versions to be:
def compare_versions(browser_name, app_path):
if str(get_last_version(browser_name)) == str(get_current_version(app_path)):
return True
else:
return False
If it solves your problem, the types of the versions are not the same.
If it doesn't work, try to print the len of the versions, maybe there is an hidden space or something like that...
In addition, try to list(version1) and list(version2) - it would split your string to list of chars and you will be able to find the diff more easily...
I have a feeling I'm being stupid. Given this ini file:
[main]
source1 = ./testing/sdir1
sync1 = ./testing/sydir1
archive1 = ./testing/adir1
source2 = ./testing/sdir2
sync2 = ./testing/sydir2
archive2 = ./testing/adir2
[logging]
log_dir = .
log_file = pixelsync.log
log_level = DEBUG
The following code hangs:
import ConfigParser
CONFIG_FILE = 'pixelsync.ini'
def parse_config() :
"""read details from the config file"""
global CONFIG_FILE
config = ConfigParser.SafeConfigParser()
config.read(CONFIG_FILE)
index = 1
while True :
if config.has_option('main', 'source' + str(index)) and \
config.has_option('main', 'sync' + str(index)) and \
config.has_option('main', 'archive' + str(index)) :
result = ( config.get('main', 'source' + str(index)),
config.get('main', 'sync' + str(index)),
config.get('main', 'archive' + str(index)))
index += 1
else :
if index == 1 :
print "could not setup any trios from the config file. exiting."
sys.exit(1)
return result
if __name__ == '__main__' :
options = parse_config()
It hangs on the 'if' clause.
If I replace the 'if' clause with :
if config.has_option('main', 'source1' ) and \
config.has_option('main', 'sync1' ) and \
config.has_option('main', 'archive1' ) :
it doesn't hang. (doesn't do what I want since I need to loop through an arbitrary number of sets of three, but it doesn't silently hang.
Python v2.7.3 on ubuntu 12.04 (Precise), 32bit.
The reason your program hangs is it never breaks out of the loop - it goes on forever. Rather than simply setting result, you need to return it. (An alternative is to set it and then use break to break out of the loop and return, but that is somewhat roundabout. It's better to simply return it straight away.
Note that doing while True: and counting like that isn't very Pythonic, the preferred approach is to instead use itertools.count().
E.g:
import itertools
...
for index in itertools.count(1):
...
Note that this shows a design flaw. You probably want to have a way of knowing if you are never going to get a suitable result. Infinite loops are generally bad.
I want to write a program that sends an e-mail to one or more specified recipients when a certain event occurs. For this I need the user to write the parameters for the mail server into a config. Possible values are for example: serveradress, ports, ssl(true/false) and a list of desired recipients.
Whats the user-friendliest/best-practice way to do this?
I could of course use a python file with the correct parameters and the user has to fill it out, but I wouldn't consider this user friendly. I also read about the 'config' module in python, but it seems to me that it's made for creating config files on its own, and not to have users fill the files out themselves.
Are you saying that the fact that the config file would need to be valid Python makes it unfriendly? It seems like having lines in a file like:
server = 'mail.domain.com'
port = 25
...etc would be intuitive enough while still being valid Python. If you don't want the user to have to know that they have to quote strings, though, you might go the YAML route. I use YAML pretty much exclusively for config files and find it very intuitive, and it would also be intuitive for an end user I think (though it requires a third-party module - PyYAML):
server: mail.domain.com
port: 25
Having pyyaml load it is simple:
>>> import yaml
>>> yaml.load("""a: 1
... b: foo
... """)
{'a': 1, 'b': 'foo'}
With a file it's easy too.
>>> with open('myconfig.yaml', 'r') as cfile:
... config = yaml.load(cfile)
...
config now contains all of the parameters.
I doesn't matter technically proficient your users are; you can count on them to screw up editing a text file. (They'll save it in the wrong place. They'll use MS Word to edit a text file. They'll make typos.) I suggest making a gui that validates the input and creates the configuration file in the correct format and location. A simple gui created in Tkinter would probably fit your needs.
I've been using ConfigParser. It's designed to read .ini style files that have:
[section]
option = value
It's quite easy to use and the documentation is pretty easy to read. Basically you just load the whole file into a ConfigParser object:
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('configfile.txt')
Then you can make sure the users haven't messed anything up by checking the options. I do so with a list:
OPTIONS =
['section,option,defaultvalue',
.
.
.
]
for opt in OPTIONS:
section,option,defaultval = opt.split(',')
if not config.has_option(section,option):
print "Missing option %s in section %s" % (option,section)
Getting the values out is easy too.
val = config.get('section','option')
And I also wrote a function that creates a sample config file using that OPTIONS list.
new_config = ConfigParser.ConfigParser()
for opt in OPTIONS:
section,option,defaultval = opt.split(',')
if not new_config.has_section(section):
new_config.add_section(section)
new_config.set(section, option, defaultval)
with open("sample_configfile.txt", 'wb') as newconfigfile:
new_config.write(newconfigfile)
print "Generated file: sample_configfile.txt"
What are the drawbacks of such a solution:
ch = 'serveradress = %s\nport = %s\nssl = %s'
a = raw_input("Enter the server's address : ")
b = 'a'
bla = "\nEnter the port : "
while not all(x.isdigit() for x in b):
b = raw_input(bla)
bla = "Take care: you must enter digits exclusively\n"\
+" Re-enter the port (digits only) : "
c = ''
bla = "\nChoose the ssl option (t or f) : "
while c not in ('t','f'):
c = raw_input(bla)
bla = "Take care: you must type f or t exclusively\n"\
+" Re-choose the ssl option : "
with open('configfile.txt','w') as f:
f.write(ch % (a,b,c))
.
PS
I've read in the jonesy's post that the value in a config file may have to be quoted. If so, and you want the user not to have to write him/her-self the quotes, you simply add
a = a.join('""')
b = b.join('""')
c = c.join('""')
.
EDIT
ch = 'serveradress = %s\nport = %s\nssl = %s'
d = {0:('',
"Enter the server's address : "),
1:("Take care: you must enter digits exclusively",
"Enter the port : "),
2:("Take care: you must type f or t exclusively",
"Choose the ssl option (t or f) : ") }
def func(i,x):
if x is None:
return False
if i==0:
return True
elif i==1:
try:
ess = int(x)
return True
except:
return False
elif i==2:
if x in ('t','f'):
return True
else:
return False
li = len(d)*[None]
L = range(len(d))
while True:
for n in sorted(L):
bla = d[n][1]
val = None
while not func(n,val):
val = raw_input(bla)
bla = '\n '.join(d[n])
li[n] = val.join('""')
decision = ''
disp = "\n====== If you choose to process, =============="\
+"\n the content of the file will be :\n\n" \
+ ch % tuple(li) \
+ "\n==============================================="\
+ "\n\nDo you want to process (type y) or to correct (type c) : "
while decision not in ('y','c'):
decision = raw_input(disp)
disp = "Do you want to process (type y) or to correct (type c) ? : "
if decision=='y':
break
else:
diag = False
while not diag:
vi = '\nWhat lines do you want to correct ?\n'\
+'\n'.join(str(j)+' - '+line for j,line in enumerate((ch % tuple(li)).splitlines()))\
+'\nType numbers of lines belonging to range(0,'+str(len(d))+') separated by spaces) :\n'
to_modify = raw_input(vi)
try:
diag = all(int(entry) in xrange(len(d)) for entry in to_modify.split())
L = [int(entry) for entry in to_modify.split()]
except:
diag = False
with open('configfile.txt','w') as f:
f.write(ch % tuple(li))
print '-*- Recording of the config file : done -*-'