PyDev/Python3.1 子进程错误 - 未声明编码

0 投票
1 回答
1601 浏览
提问于 2025-04-17 09:04

当我运行Parent.py,它调用了子进程child.exe时,出现了以下错误

  File "child.exe", line 1
SyntaxError: Non-UTF-8 code starting with '\x90' in file child.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

如果我用child.py运行Parent.py,执行成功并从Eclipse返回了“Hello from parent.”

但是如果我从自带的IDLE运行Parent.py,无论是child.exe还是child.py都没有任何返回结果。

我看过http://python.org/dev/peps/pep-0263/的文档,并且理解了它,可能误解了意思,以为我应该添加建议的注释,我尝试把这些注释加到child.exe上……但没有效果。


Parent.py

import os
import subprocess
import sys

if sys.platform == "win32":
    import msvcrt
    import _subprocess
else:
    import fcntl

# Create pipe for communication
pipeout, pipein = os.pipe()

# Prepare to pass to child process
if sys.platform == "win32":
    curproc = _subprocess.GetCurrentProcess()
    pipeouth = msvcrt.get_osfhandle(pipeout)
    pipeoutih = _subprocess.DuplicateHandle(curproc, pipeouth, curproc, 0, 1,
            _subprocess.DUPLICATE_SAME_ACCESS)

    pipearg = str(int(pipeoutih))  
else:
    pipearg = str(pipeout)

    # Must close pipe input if child will block waiting for end
    # Can also be closed in a preexec_fn passed to subprocess.Popen
    fcntl.fcntl(pipein, fcntl.F_SETFD, fcntl.FD_CLOEXEC)

# Start child with argument indicating which FD/FH to read from
subproc = subprocess.Popen(['python', 'child.exe', pipearg], close_fds=False)

# Close read end of pipe in parent
os.close(pipeout)
if sys.platform == "win32":
    pipeoutih.Close()

# Write to child (could be done with os.write, without os.fdopen)
pipefh = os.fdopen(pipein, 'w')
pipefh.write("Hello from parent.")
pipefh.close()

# Wait for the child to finish
subproc.wait()



Child.exe(用cx_freeze打包的)

import os, sys


if sys.platform == "win32":
    import msvcrt

# Get file descriptor from argument
pipearg = int(sys.argv[1])
if sys.platform == "win32":
    pipeoutfd = msvcrt.open_osfhandle(pipearg, 0)
else:
    pipeoutfd = pipearg

# Read from pipe
# Note:  Could be done with os.read/os.close directly, instead of os.fdopen
pipeout = os.fdopen(pipeoutfd, 'r')
print(pipeout.read())
pipeout.close()

1 个回答

2
subprocess.Popen(['python', 'child.exe', pipearg], ...

问题在于你试图让Python读取一个二进制文件,如果child.exe是一个普通的Windows可执行文件的话。出现这个错误是因为二进制文件的字节超出了标准的ASCII或UTF-8标准,所以解释器无法读取它。

也许你想要的只是执行child.exe,直接把Python那一行去掉就可以了:

subprocess.Popen(['child.exe', pipearg], ...

撰写回答