尝试使用Popen从另一个python脚本打开python脚本会抛出windowse

2024-05-15 22:54:24 发布

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

我试图在python2.7中使用Popen从另一个python脚本打开一个python脚本。在

这两个脚本是:

儿童.py:逐个获取5个整数,然后等待一段时间并打印其平方

    import time
    for i in range(5):
        value = int(raw_input('Enter an integer: '))
        time.sleep(2)
        print "Its square is ", value*value

父级.py:打开儿童.py并将5个int写入其stdin并打印其stdout

^{pr2}$

下面是我在中Popen构造函数的第一个参数时使用的其他替换父级.py在stackoverflow中看到许多类似的问题后

    "./child.py": Same WindowsError is produced
    <full path>:  Same WindowsError is produced
    ["python", "child.py"]: Did not raise error but opened python (useless)

产生的窗口错误是:

    WindowsError: [Error 193] %1 is not a valid Win32 application

Tags: py脚本childtimeisvaluenot整数
2条回答

如果有Python解释器设置来处理*.py文件,那么只需在Popen构造函数中设置shell=True

child_program = subprocess.Popen("child.py",
                                 shell=True,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)

正如其他人所指出的,这个方法带有一个安全警告,因此您必须注意传递给Popen的参数不是恶意构造的(例如,如果您从用户输入中获取一些参数):https://docs.python.org/3/library/subprocess.html#security-considerations

否则,您需要告诉Popen使用Python可执行文件来加载文件,如下所示:

^{pr2}$

在此上下文中,sys.executable将解析为用于启动父脚本的Python二进制文件的完整路径。在

首先,必须指定要作为子进程打开的文件类型

 child_program = subprocess.Popen(['executable','child.py'], 
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)

这应该可以解决您的问题。在

默认值为shell=FalsePopen在Windows中委托给CreateProcess,比如its docs。该API函数只能运行可执行文件(不管其扩展名如何)。在

你也需要

  • {前导参数^添加}
  • 使用将委托给ShellExecute的机制,该机制将根据文件类型关联运行上述命令行。E、 g.指定shell=True(注意文档中的安全警告),因为^{} falls back to ^{} for non-executable files。在

相关问题 更多 >