繁体   English   中英

简单的 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 ,它存在安全隐患, 文档中也给出了这一点-

执行包含来自不受信任来源的未经处理的输入的 shell 命令会使程序容易受到 shell 注入,这是一个严重的安全漏洞,可能导致任意命令执行。 因此,在命令字符串是从外部输入构造的情况下,强烈建议不要使用 shell=True:

此外,如果您不想使用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()才能运行它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM