What is the difference between using eval(*code*) and just *code*? - python

What is the difference between:
cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))
and:
cerebro.addsizer(bt.sizers.FixedSize, dict(args.sizer))?
I ran the first one and it worked but the second one causes an error.
Can someone please help me?

Python’s eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you’re trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.

Related

How can I turn a string that contains numbers and operators into a result?

I want to convert this string into a result n for the output to be 11.
a = "1+5*6/3"
print (a)
The eval() built-in function can evaluate a Python expression including any arithmetic expression. But note the eval() function is a security concern because it can evaluate any arbitrary Python expression or statement so should be used only if the input to evaluate is controlled and trusted user input. There are examples to why eval() is dangerous in this question.
a = "1+5*6/3"
result = eval(a)
print(result)
Output:
11.0
Using ast module as an alternative to eval()
A safe alternative to eval() is using ast.literal_eval. Recent Python 3 versions disallows passing simple strings to ast.literal_eval() as an argument. Now must parse the string to buld an Abstract Syntax Tree (AST) then evaluate it against a grammar. This related answer provides an example to evaluate simple arithmetic expressions safely.
You can directly use the python eval function.
a = eval("1+5*6/3")
print(a)

Net Use in Python 3

anyone could help me with python trying to use NET use, I don't know the diferences between / in python and perl, because code in perl works
$runMap = "C:\\Windows\\System32\\net.exe use \\\\$ip\\D\$ /persistent:no /user:$user_name $passwd";
system($runMap);
But in Python 3 don't work
os.system("C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:user pass")
Perl is using interpolation, that is, it is possible to embed variables inside a double quoted string, since Perl 5 interpolated variables start with a $ or a # marker. In your case you are embedding $user_name and $passwd.
Python variable names are not prefixed by a "magic character" (sigil), so you cannot embed them inside strings except by using formatting statements. There are a couple of regimes, here is one which is a similar idea to printf:
cmd = "C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:%s %s" % (username, passwd)
os.system(cmd)
As an ex-Perlmonger I missed interpolation so much I wrote a Python module to support it. While I learnt a lot about Python doing it, it was otherwise a waste of time. Python programming is a different style, you don't need interpolation any more.
By the way, unlike Perl's system(), Python's os.system() will always spawn a shell (as does C's). Therefore it is generally considered to be deprecated. The subprocess.Popen() method gives much more control.
EDIT:
With the advent of Python 3.6 and Literal String Interpolation (specified in PEP 498) - more commonly known as f-strings - my original post needs another way to do it.
Single or double quotes may be used, even triple quotes. Basically we just put the Python expression, commonly a variable, inside braces (similar to Ruby).
So, for example:
os.system(f"C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:{username} {passwd}")
The comment about subprocess.Popen() is also out of date, since Python 3.5 the preferred interface is now subprocess.run().

Parsing list to create python code

I have a list that I have successfully converted into a python statment
ex:
from operator import mul,add,sub,abs
l = ['add(4,mul(3,abs(-3)))']
I was wondering what would I use to RUN this string as actual python code? I should be expecting a output of 13. I want to input the 0th value of the list into a function that is able to run this value as actual python code.
You don't want to run this as Python code. You're trying to parse expressions in some language that isn't Python, even if it may be superficially similar. Even if it's a proper subset of Python, unless, say, __import__('os').system('rm -rf /') happens to be a valid string in the language that you want to handle by erasing the hard drive, using eval or exec is a bad idea.
If the grammar is a proper subset of Python, you can still use the ast module for parsing, and then write your own interpreter for the parsed nodes.
However, I think what you really want to do here is build a very simple parser for your very simple language. This is a great opportunity to learn how to use a parsing library like pyparsing or a parser-generator tool like pybison, or to build a simple recursive-descent parser from scratch. But for something this simple, even basic string operations (splitting on/finding parentheses) should be sufficient.
Here's an intentionally stupid example (which you definitely shouldn't turn in if you want a good grade) to show how easy it is:
import operator
OPERATORS = operator.__dict__
def evaluate_expression(expr):
try:
return int(expr)
except ValueError:
pass
op, _, args = expr.rpartition('(')
rest, _, thisop = op.rpartition(',')
args = args.rstrip(')').split(',')
argvalues = map(int, args)
thisvalue = OPERATORS[thisop](*argvalues)
if rest:
return evaluate_expression('{},{}'.format(rest, thisvalue))
return thisvalue
while True:
expr = input()
print(evaluate_expression(expr))
Normally, you want to find the outermost expression, then evaluate it recursively—that's a lot easier than finding the rightmost, substituting it into the string, and evaluating the result recursively. Again, I'm just showing how easy it is to do even if you don't do it the easy way.
use exec like this:
exec('add(4,mul(3,abs(-3)))')
That should work
more about exec
If you want to evaluate a Python expression, use eval. This returns the value of the evaluated expression. So, for example:
>>> eval(l[0])
13
>>> results = [eval(expr) for expr in l]
>>> results
[13]
However, any time you find yourself using eval (or exec or related functionality), you're almost always doing something wrong. This blog post explains some of the reasons why.
since you're evaluating an expression, eval would suit you better than exec. Example:
x = -3
y = eval('add(4,mul(3,abs(x)))')
print y
Note the security implication of exec and eval, since they can execute arbitrary code, including for example deleting all files you have access, installing Trojans to your doc files, etc.
Check out also ast.literal_eval for python 2.6+.

Why would this line throw a syntax error in Python

I am getting a syntax error on this line of code in Python (tried in both 2.7.5 and 3.3)
Can someone tell me what is wrong?
if (ctx.bytes[0] = t + len) < t:
Appreciate any help!
Added 10/31/2013: My problem has stemmed from the fact that an online converter probably converted the code badly from C to Python. So I REALLY need help on how to convert this program to Python (will prefer 3, but 2 is fine). I need a lot of help with this because I don't 1) understand fully what the C code is doing and 2) I am still very new to Python! So help is appreciated!!! The full C source is posted at Pastebin here: http://pastebin.com/JTT1srSb.
Python won't let you use a single equals sign (assignment operator) within a conditional expression, unlike languages like C. Instead, try doing the following:
ctx.bytes[0] = t + len
if ctx.bytes[0] < t:
Unlike C, the assignment operator does not return any value and so can not be used in expressions. Python's if statement's condition has to be an expression. You can replace your code with:
ctx.bytes[0] = t + len
if len:
PS: You don't need to put brackets around the condition of an if statement in Python.
(ctx.bytes[0] = t + len) < t
You are using assignment operator (=) in the boolean expression, which is not allowed in python.

Python logical NOT operator for regular expressions

I tried searching for this answer online but I haven't found any luck. I am wondering if python supports a logical not operator (usually '!') in other languages for an if statement, or any control statement really. For example, I am looking to achieve this functionality.
if !(re.search('[0-9]', userInputVariable):
fix error and report to user
...Proceed with rest of code...
Where basically if the user does not input a number I correct it to a default value and proceed with script
Thanks!
You're looking for the not operator.
But that's not how you check for a number.
try:
int(userInputVariable)
except ValueError:
print "Not a number"
...
if not userInputVariable.isdigit():

Categories