I'm trying to convert to get a command executed which is passed to the print statement. Eg:
print "exec(raw_input())"
Can I get to run the exec() in some way?
do this
command = raw_input("Command: ")
exec(command)
why are you trying to print it? be more clear if this isnt what you are looking for
I Guess this is what you are looking for ?
>>> exec("x = raw_input()")
23
>>> x
'23'
>>>
Are you asking for something simple like
aString = "raw_input()"
print "exec(" + aString + ")"
exec(aString)
from __future__ import print_function
def foo(x):
exec x
print = foo
print("exec(raw_input())")
Running
% test.py
kaboom
results in:
NameError: name 'kaboom' is not defined
From the tags you applied, it seems like you're looking for a magic string that will allow you to run any arbitrary code when Python passes that string to the print statement.
There are no such known strings. You might try very long strings, just over the obvious boundaries, looking for the traditional stack- and heap-overflow cases, but if you find one in Python X.Y.Z, chances are it was already fixed in X.Y.Z+1.
If the Python script is actually doing an exec or eval on your string, of course that's easy to exploit; if it's just doing a print, the contents never even get compiled, much less run; they're just a plain old string. The fact that the string happens to have dangerous-looking things like exec in it is irrelevant; it's not more exploitable than getting Python to print the string "rm -rf /".
Of course if you can arrange for the output of one Python interpreter to feed in as the input to an interactive session in another interpreter, then whatever you get the first interpreter to print will get executed in the second one… but in that case, you don't need the exec in the middle of the string anyway.
The print statement writes to sys.stdout by default, and sys.stdout is like a file. You can make a class that looks like a file, with a write method, which would be called by the print statement. I put together a script which demonstrates this, print_exec.py. Also note, this doesn't work if the code in the print statement contains print, itself. i.e., print "print 'foo'" won't work. So, in the example, I had to print to sys.stderr to actually see something happening. Hope this helps.
print_exec.py
import sys
class file_like(object):
def write(self, x):
exec(x)
sys.stdout = file_like()
y = "exec(raw_input())"
print "exec(y)"
Example running the print_exec.py:
>python print_exec.py
print "import sys; print >> sys.stderr, 'hi'"
hi
>
Related
I am trying to create a variable to be used in more than one place to print a line of script
I tried using this to print: print(helped), didn't work, it gave the error you see. I tried doing this: print helped(), gave a syntax error
def helped():
print('''Type
Type
Type''')
weirdness = input('''What function would you like to run?
Type "Help" for possible commands ''')
if weirdness.upper() == "HELP":
print (helped)
When I enter "helped" upon being prompted, I get:
What function would you like to run?
Type "Help" for possible commands helped
I think you need a bit of help
instead of getting the print statement
How do i resolve the issue such that this wont happen?
In Python when calling a function, you must use the parentheses. So since your function's name is helped, you should call it like this:
print( helped() )
You should do this regardless of whether your function has parameters.
On a side note, with Python 2.6, you could have also use the print function without parentheses like this:
print helped()
but this is not the case with Python 3.x
You simply need to execute the function. Currently, the helped() function is defined but not run in your code. Essentially, it's never used. Right now you use print (helped) and should be getting a error when instead, you should call the function
Change
print(helped)
to
print(helped())
Using Python 3, I have a console application that I am porting to a GUI. The code has a bunch of print statements, something like this:
print(f1(), f2(), f3(), sep=getsep(), end=getend())
I would like to convert these calls into something like:
GuiPrintLine(f1(), f2(), f3(), sep=getsep(), end=getend())
where each line is eventually rendered using some (undefined) GUI framework.
This is easy to do if I can convert the arguments to print into to the string that print would normally produce without the side-effect of actually printing to sysout. In other words, I need a function like this:
s = print_to_string(*args, **kwargs)
How do I format a set of parameters to print(...) into a single string that produces the same output as print() would produce?
I realize I could emulate print by concatenating all the args with sep and ends, but I would prefer to use a built-in solution if there is one.
Using print and redirecting sysout is not attractive since it requires modifying the global state of the app and sysout might be used for other diagnostics at the same time.
It seems like this should be trivial in Python, so maybe I'm just missing something obvious.
Thanks for any help!
Found the answer via string io. With this I don't have to emulate Print's handling of sep/end or even check for existence.
import io
def print_to_string(*args, **kwargs):
output = io.StringIO()
print(*args, file=output, **kwargs)
contents = output.getvalue()
output.close()
return contents
My solution :
def print_to_string(*args, **kwargs):
newstr = ""
for a in args:
newstr+=str(a)+' '
return newstr
I want to pass function definition to a python command line script. What is the best way to do this? I am using python 2. Suppose i have a script like this:
#myscript.py
x = load_some_data()
my_function = load_function_definition_from_command_line()
print my_function(x)
And i want to call it like this: python myscript.py 'def fun(x): return len(x)'
How do i perform the load_function_definition_from_command_line part ?
I imagine a workaround:
get the string function definition from command line
write it to a file with .py extension in some temp directory
load the definition from file using solutions from this question: How to import a module given the full path?
execute
cleanup
But I am sure there must be a better way.
You can use eval to run code defined in a string. Like so:
import sys
x = load_some_data()
function = eval("".join(sys.argv[1:]))
print(function(x))
With your specific example though you might have to use something like lambda x: len(x)
As #Jan-Spurny rightly points out: "Never, never, never use eval unless you're absolutely sure there is no other way. And even then you should stop and think again."
In my mind the better strategy would be to turn the data loader and executor into a module with a method that takes a function as an argument and runs the desired code. The end result something like this:
import data_loader_and_executor
def function(x):
return len(x)
data_loader_and_executor.run(function)
You can use eval or exec to create a function in your current namespace.
exec "somefunc(x): return x * 2"
somefunc(2) # 2
Example within your context
python load_function.py "def f(x): return x * 2"
//load_function.py
import sys
exec sys.argv[1]
print f(2)
Command line output:
4
Edit: Obligatory, "It is not wise to execute user input like this."
Use function exec:
import sys
def load_function_definition_from_command_line():
exec(sys.argv[1])
return locals()['fun']
Of course you have to know, how your function will be named, but this can be done by passing to your argument second argument:
$ python myscript.py 'def fun(x): return len(x)' fun
And then your function will look like:
import sys
def load_function_definition_from_command_line():
exec(sys.argv[1])
return locals()[sys.argv[2]]
!!Remember though, that evaluating user input is very dangerous!!
Edit: Since fun would be the only object defined in locals, you can just return first element in locals():
def load_function_definition_from_command_line():
exec(sys.argv[1])
return locals()[0]
The most obvious source for the correct answer on how to do this is in the timeit python builtin library.
It is invoked like this:
$ python -m timeit '"-".join(str(n) for n in range(100))'
and you can find the source code here, which uses compile and exec to invoke the code from the command line
https://hg.python.org/cpython/file/2.7/Lib/timeit.py#l143
I am trying to read a string in a python script within vim, but something goes wrong. I do it in a function getting an argument called key, using s = vim.eval("a:key"), but this is a simpler example demonstrating the problem:
:py import vim
:py s = vim.eval("'foo'")
:py print s # this prints 'foo' (without the quotes)
:py if s is 'foo': print 'yes' # this doesn't print 'yes'
The problem is that s is 'foo' does not evaluate to True. My guess is that it has something to do with vim.eval, but it's only a guess.
Can anyone explain what is the difference between Popen and exec in Python
Im able to accomplish the same task to execute a program dynamically using exec and Popen.
The code here uses the EXEC approach but what will happen if I use the Popen approach.
code1.py
def runjob(src, job):
x = "from {src} import *" + '\n' + "{job}(parm1=)"
y = x.format(src=src, job=job)
exec ( 'from ' + src + ' import *' + '\n' + job + '(10)' )
def main():
runjob(c:/python27/test_job', 'il')
code2.py
def fl(parm=None):
print 'function1'
print parm
def f2(parm=None):
print 'function 2'
print parm
def f3(parm=None):
print 'function 3'
print parm
exec and Popen are more or less unrelated.
exec is used to run a piece of python code.
This statement supports dynamic execution of Python code. The first expression should evaluate to either a string, an open file object, or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). If it is an open file, the file is parsed until EOF and executed.
Popen is a class that allows to you to run any programm.
Execute a child program in a new process. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.
Not only can you run other programms, you can also read their output and set a number of usefull options, like the working directory or if a new terminal should be opened etc.