【问题标题】:Simple Python Script not Executing Properly简单的 Python 脚本无法正确执行
【发布时间】:2015-09-04 16:26:02
【问题描述】:

代码如下:

    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 有点陌生。

【问题讨论】:

    标签: python windows subprocess


    【解决方案1】:

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

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

    执行包含来自不受信任来源的未经处理的输入的 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() 才能运行它。

    【讨论】:

    • 好的,所以更新:我将临时文件的内容粘贴到一个新文件中,并尝试通过 Python IDE 执行它,也没有任何反应,程序终止,没有输出。这让我相信从unix到windows的脚本翻译存在问题
    • 是的,你没有在脚本中调用main()
    • 我使用的IDE在运行脚本时会自动调用main
    • not python.exe ,ide 可以调用,python.exe 不会。尝试在脚本的最后一行调用它。
    • 很高兴能为您提供帮助。我还想请您接受答案(通过单击答案左侧的勾号),这将对社区有所帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多