简单 Python 脚本未正确执行

Simple Python Script not Executing Properly

代码如下:

    fh = tempfile.NamedTemporaryFile(delete=False,suffix = '.py')
    stream = io.open(fh.name,'w',newline='\r\n')
    stream.write(unicode(script))
    stream.flush()
    stream.close()
    proc = subprocess.Popen(
        [path,fh.name], 
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    proc.stdin.close()
    proc.stderr.close()
    out = proc.stdout.readline()
    print out

script 是一个包含子流程代码的字符串,在本例中是一个简单的 hello world。因为它有 unix 文件结尾,我不得不使用 io.open 以便为 windows 正确编写它。 path 是我机器上 python.exe 的路径。文件已生成,在记事本中看起来不错:

    def main():
        print 'hello world'

但是,当我运行程序时,子进程执行但什么都不做。 这不是可执行路径的问题,我已经用其他程序测试过它,所以它必须与临时文件本身或其中的文本有关。 Delete 设置为 false 以检查文件内容以进行调试。这段代码有什么明显的错误吗?我对使用 Popen 有点陌生。

您程序中的主要问题是,当您指定 shell=True 时,您需要以字符串而不是列表的形式提供整个命令。

鉴于此,您确实没有必要使用 shell=True ,此外,除非绝对必要,否则您不应使用 shell=True ,它存在安全隐患,这在 documentation as well -

Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input:

此外,如果您不想使用 stdin / stderr(因为您在启动该过程后立即关闭它们),则无需使用 PIPE 给他们。

例子-

fh = tempfile.NamedTemporaryFile(delete=False,suffix = '.py')
stream = io.open(fh.name,'w',newline='\r\n')
stream.write(unicode(script))
stream.flush()
stream.close()
proc = subprocess.Popen(
    [path,fh.name], 
    stdout=subprocess.PIPE,
)
out = proc.stdout.readline()
print out

此外,脚本 -

def main():
    print 'hello world'

将不起作用,因为您需要调用 main() 才能将其转换为 运行。