在Python内部从命令行执行Python多行语句

2024-05-18 14:49:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有成千上万的小型多行python3程序要运行,它们被生成为字符串。它们都有类似的结构,并以print命令结束。下面是一些简单的例子

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)'

如果要从解释器运行它们,它们都应该是可执行的。我的意思是,当你打印它们的时候,它们看起来就像普通的小程序

>>> 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)

我想在我的程序中执行它们(生成它们),并将输出(即print的输出)作为变量捕获,但我被困在了如何做?你知道吗

像这样的

import os
output = os.popen("python -c " +  prog_1).read()

太好了,但我有这个错误?你知道吗

/bin/sh: 3: Syntax error: word unexpected (expecting ")")

我想问题是我不知道如何从命令行执行小程序?这行执行,但不打印??你知道吗

python -c "'h=9\nh=h+6\nprint(h)'"

非常感谢您的帮助:)


Tags: 字符串import命令程序outputos结构解释器
3条回答

如果希望在单独的进程中执行它们,则可以使用^{}

>>> 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

请注意,encoding支持需要python3.6,而subprocess.run支持需要python3.5。你知道吗

在python3.5中,需要将输入作为bytes传递,并且返回的输出也将是字节。你知道吗

>>> result = subprocess.run(["python"], input=bytes(prog_1, "utf-8"), stdout=subprocess.PIPE).stdout
>>> print(str(result, "utf-8"))
15

您可以使用exec

>>> prog_1 = 'h=9\nh=h+6\nprint(h)'
>>> exec(prog_1)
15

如果未绑定到命令行,则可以使用:

exec(prog_1)

警告exec()可能非常危险Why should exec() and eval() be avoided?

相关问题 更多 >

    热门问题