1

Is it possible to run a Python script which has been saved as a variable?

x = 'print ("Hello, World!")'
??? run(x) ???

I would like to be able to run the script without having to run:

python -c 'print ("Hello, World!")'

Any help will be appreciated.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Ritashugisha
  • 93
  • 2
  • 9

2 Answers2

1

I believe the exec statement is what you're looking for.

>>> cmd = 'print "Hello, world!"'
>>> exec cmd
Hello, world!
>>>
>>> cmd = """
... x = 4
... y = 3
... z = x*y + 1
... print 'z = {0}'.format(z)
... """
>>>
>>> exec cmd
z = 13

Please take appropriate cautions if you are including any user input in the string you are going to exec. Someone could easily input malicious statements that would be executed.

See also:

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
0

Depending what you want to do, it might help more to have another file and use Subprocess.Popen to open it as well. An example being asynchronous processes, a backend database, or another instance of an application to allow for a clean API between multiple processes :).

From the subprocess docs:

">>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!"

Subprocess Docs

Additionally you can use eval(expression[, globals[, locals]]) which provides a more intuitive way for giving a symbol table (ok a namespace dictionary technically) to the string to be run :).

Eiyrioü von Kauyf
  • 4,481
  • 7
  • 32
  • 41