[英]Executing Python multi-line statements from command-line, while inside python
I've got thousands of small multi-line python3 programs to run, which are generated as strings. 我有成千上万的小型多行python3程序要运行,它们是作为字符串生成的。 They all have a similar structure, and end with a print
command. 它们都具有相似的结构,并以print
命令结尾。 Here's some simple examples 这是一些简单的例子
prog_1 = 'h=9\nh=h+6\nprint(h)'
prog_2 = 'h=8\nh-=2\nprint(h)'
prog_3 = 'c=7\nc=c+4\nprint(c)'
They should all be executable if you were to run them from the interpreter. 如果要从解释器运行它们,它们都应该是可执行的。 What I mean is, they look like small normal programs when you print them, 我的意思是,当您打印它们时,它们看起来像小型的普通程序,
>>> print(prog_1)
h=9
h=h+6
print(h)
>>> print(prog_2)
h=8
h-=2
print(h)
>>> print(prog_3)
c=7
c=c+4
print(c)
I want to execute them from inside my program, (which generates them), and capture the output, (ie the output of the print
) as a variable, but I'm stuck how to do it? 我想从我的程序内部执行它们(生成它们),然后将输出(即print
输出)捕获为变量,但是我被困在该怎么做?
Something like 就像是
import os
output = os.popen("python -c " + prog_1).read()
would be great but I get this error? 会很好,但是我得到这个错误?
/bin/sh: 3: Syntax error: word unexpected (expecting ")")
I think the problem is I don't know how to execute the small programs from the command line? 我认为问题是我不知道如何从命令行执行小程序? This line executes, but does not print out?? 该行执行,但不打印出来?
python -c "'h=9\nh=h+6\nprint(h)'"
Thanks a lot for your help :) 非常感谢你的帮助 :)
If you are not bound to command line you can use: 如果您不限于命令行,则可以使用:
exec(prog_1)
Warning : exec()
can be very dangerous - Why should exec() and eval() be avoided? 警告 : exec()
可能非常危险- 为什么应避免使用exec()和eval()?
You can use exec
: 您可以使用exec
:
>>> prog_1 = 'h=9\nh=h+6\nprint(h)'
>>> exec(prog_1)
15
If you wish to execute them in a separate process then you can use subprocess.run
: 如果希望在单独的过程中执行它们,则可以使用subprocess.run
:
>>> prog_1 = 'h=9\nh=h+6\nprint(h)'
>>> result = subprocess.run(["python"], input=prog_1, encoding="utf-8", stdout=subprocess.PIPE).stdout
>>> print(result)
15
Note that Python 3.6 is required for encoding
support, and Python 3.5 is required for subprocess.run
. 需要注意的是Python的3.6所需的encoding
支持,和Python 3.5需要subprocess.run
。
In Python 3.5, you need to pass the input as bytes
, and the returned output will also be bytes. 在Python 3.5中,您需要将输入作为bytes
传递,返回的输出也将是字节。
>>> result = subprocess.run(["python"], input=bytes(prog_1, "utf-8"), stdout=subprocess.PIPE).stdout
>>> print(str(result, "utf-8"))
15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.