簡體   English   中英

在python內部時從命令行執行Python多行語句

[英]Executing Python multi-line statements from command-line, while inside 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)'"

非常感謝你的幫助 :)

如果您不限於命令行,則可以使用:

exec(prog_1)

警告exec()可能非常危險- 為什么應避免使用exec()和eval()?

您可以使用exec

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

如果希望在單獨的過程中執行它們,則可以使用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

需要注意的是Python的3.6所需的encoding支持,和Python 3.5需要subprocess.run

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM