I want to pass some custom options to the linker based what is in a header file in my source tree. I'm doing something like this now and it works, but there's got to be a better way:
def getCustomStr():
for l in open(Dir('#').abspath + "/header.h"):
if "#define MAGIC_FLAG" in l:
return munge_flag(l)
env.Append(LINKFLAGS['-Xlinker', getLinkOpt()])
In particular accessing Dir('#') like that gives me the creeps. Any better ideas?
If Dir('#') gives you the creeps, try this instead:
for l in open(File('header.h').abspath):
Related
I want to use printing command bellow in many places of my script. But I need to keep replacing "Survived" with some other string.
print(df.Survived.value_counts())
Can I automate the process by formating variable the same way as string? So if I want to replace "Survived" with "different" can I use something like:
var = 'different'
text = 'df.{}.value_counts()'.format(var)
print(text)
unfortunately this prints out "df.different.value_counts()" as as a string, while I need to print the value of df.different.value_counts()
I'm pretty sure alot of IDEs, have this option that is called refactoring, and it allows you to change a similar line of code/string on every line of code to what you need it to be.
I'm aware of VSCode's way of refactoring, is by selecting a part of the code and right click to select the option called change all occurances. This will replace the exact code on every line if it exists.
But if you want to do what you proposed, then eval('df.{}.value_counts()'.format(var)) is an option, but this is very unsecured and dangerous, so a more safer approach would be importing the ast module and using it's literal_eval function which is safer. ast.literal_eval('df.{}.value_counts()'.format(var)).
if ast.literal_eval() doesn't work then try this final solution that works.
def cat():
return 1
text = locals()['df.{}.value_counts'.format(var)]()
Found the way: print(df[var].value_counts())
Is there a way, beside parsing the file, to display the comments in a Python file ?
As in :
d = {
# key value uses
k = v
}
I would display :
# key value uses
in the function __doc__.
Thanks
Python always deletes (and docstrings not at the beginning of a definition). So you'll have to parse the source yourself if you want to extract them.
The standard library's ast module also drops comments, but you could take a look at the tokenize module, which returns them. (However, it doesn't parse, so you'd still need to do some work to associate the comment with its function or class or whatever.)
I have the following code snippet which is part of a larger chunk of code to extract image filenames from links.
for a in soup.find_all('a', href=True):
url = a['href']
path, file = url.rsplit('/', 1)
name, ext = file.rsplit('.', 1)
It works very well, however on occasion the data (which comes from an external source) will have errors.
Specifically, the last line in the snippet above will throw an error that:
name, ext = file.rsplit('.', 1)
ValueError: not enough values to unpack (expected 2, got 1)
What is the best way to ignore this error (or lines containing input not as expected) and continue on to the next entry?
I would have thought a try and catch is the right approach here, but upon googling how to do that with this type of error I did not find anything.
Is it possible to use a try block to catch this type of error? If not, why not, and what is the better approach?
Assuming all you need is to ignore the error, this try/except style should work for you:
for item in ['a.b.c', 'a.b', 'a', 'a.b.c']:
try:
path, file = item.rsplit('.',1)
print("%s, %s" % (path, file))
except ValueError:
print("error with %s" % item)
continue
print("more work here!")
which gives the output:
a.b, c
more work here!
a, b
more work here!
error with a
a.b, c
more work here!
Of course, this may not be the best solution to use, depending on the greater context of what you are trying to do. Is it safe to just ignore the files with no extensions?
In particular, you should generally try to sanitize incoming data as much as possible before processing it, though this is a relatively trivial example and its likely that sanitizing the data for this would be just as expensive as doing this particular split. Put another way, user input being dirty isn't really an "exceptional" condition.
I would not use a try-except in this case, since you have no use for the except part. You're not going to be processing the file if you do encounter an error. Feel free to read up on try-excepts, there are tons of questions on stack overflow about it to see what you think will work best for you.
It sounds like you don't understand the error. The error is because you must have a filename that doesn't have an extension. so when you do rsplit, it only has 1 value. For example:
file = 'babadabooey'
print(file.rsplit('.', 1))
Out: ['babadabooey']
So if you try to unpack that into two values, you're going to get an error. I assume, most of the time you are expecting something like
file = 'babadabooey.exe'
print(file.rsplit('.', 1))
Out: ['babadabooey', '.exe']
So if you try to unpack that value into two values, you're fine. How I would proceed is with an if statement, that way you only try to split it IF '.' is in the file var.
if '.' in file:
name, ext = file.rsplit('.', 1)
I am working on using clang bingings python to travers c/c++ code into AST,how can I get a tree based AST structure?
Some pointers on where to start, tutorials or anything in this regard will be of great help!!!
I found a very useful work(If you want to check this out ,here is the link:https://www.chess.com/blog/lockijazz/using-python-to-traverse-and-modify-clang-s-ast-tree) and tried his code,unfortunately I didn't get a useful output.
function_calls = []
function_declarations = []
def traverse(node):
for child in node.get_children():
traverse(child)
if node.type == clang.cindex.CursorKind.CALL_EXPR:
function_calls.append(node)
if node.type == clang.cindex.CursorKind.FUNCTION_DECL:
function_declarations.append(node)
print 'Found %s [line=%s, col=%s]' % (node.displayname, node.location.line, node.location.column)
clang.cindex.Config.set_library_path("/Users/tomgong/Desktop/build/lib")
index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
root = tu.cursor
traverse(root)
Just in case anyone was having trouble still, I found that if you should be using kind instead of type
you can run clang.cindex.CursorKind.get_all_kinds() to retrieve all kinds and see that when using the node.type does not appear in any of them.
function_calls = []
function_declarations = []
def traverse(node):
for child in node.get_children():
traverse(child)
if node.kind == clang.cindex.CursorKind.CALL_EXPR:
function_calls.append(node)
if node.kind == clang.cindex.CursorKind.FUNCTION_DECL:
function_declarations.append(node)
print 'Found %s [line=%s, col=%s]' % (node.displayname, node.location.line, node.location.column)
clang.cindex.Config.set_library_path("/Users/tomgong/Desktop/build/lib")
index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
root = tu.cursor
traverse(root)
how can I get a tree based AST structure?
The translation unit object's cursor (tu.cursor) is actually the start node of an AST. You might wanna use clang tool to visually analyze the tree. Maybe this will shed the light and give you the intuition on how to work with the tree.
clang++ -cc1 -ast-dump test.cpp
But basically, it boils down to getting children nodes of the main node (tu.cursor) and recursively traversing them, and getting to the nodes which are of interest to you.
You might wanna also check an article from Eli Benderski how to start working with the python binding:
https://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang#id9
unfortunately I didn't get a useful output.
You might run into incomplete or wrong parsing, when you don't provide paths to includes in the parsed file to libclang module. For example, if the source file you want to parse uses some of the QT includes, then you need to specify relevant include paths in the parse() call like in the example here:
index = clang.cindex.Index.create()
tu = index.parse(src_file, args = [
'-I/usr/include/x86_64-linux-gnu/qt5/',
'-I/usr/include/x86_64-linux-gnu/qt5/QtCore'])
Also look for some comments in the libclang.cindex python module, they can help you. For example, I found the solution above by reading those comments.
I have been using pycparser in order to do obtain the AST of C/C++ source code and explore the same using python.
You can find the API for exploring the AST in this example from the repository.
In Groovy, I get my hands on a Hudson job:
def job = hudson.model.Hudson.instance.getItem("Rsync library to docs-stage")
Now I would like to have a list of the parameter names for that job. Sounds simple, but Googling around isn't getting me there yet. Could someone enlighten me?
Thanks.
I'n not sure what you mean by "parameter names." As a last resort, you can get the configuration of the job as an XML String:
print job.configFile.asString()
Since this is XML, you can parse it as needed. Depending on what parameter names you are looking for, you can probably also get them directly in Java. Can you post the XML for what you are looking for? That will help in commenting on a better way.
For the parameters needed by this poster, it is easy to get using Groovy:
def params = job.getProperty('hudson.model.ParametersDefinitionProperty')
.parameterDefinitions
params.each { p -> println "$p.name"}