我需要运行一个程序,并通过使用子进程模块在python脚本中使用其控制台输出。这是我的代码:
#!/usr/bin/python
# coding=utf-8
from __future__ import unicode_literals
import sys
from subprocess import Popen, PIPE, STDOUT
# Check the code by running linux list command
p = Popen(["ls", "-l"], stdout=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print line
p.wait() # wait for the subprocess to exit
# Run the C hello world program
p = Popen([sys.executable, "hello_C"], stdout=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print line
p.wait() # wait for the subprocess to exite
在Python控制台中显示“ ls -l”输出没有问题。我假设与子流程和读取stdout有关的代码是正确的。但是,当我尝试运行hello_C程序(它只是一个hello world程序)时,会出现以下错误:
File "hello_C", line 1
SyntaxError: Non-ASCII character '\xff' in file hello_C on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
sys.executable
是Python解释器。 Sys hello_C
是已编译的C程序,而不是Python脚本,您不应使用它来运行该程序。只需直接运行该程序。
p = Popen(["./hello_C"], stdout=PIPE, bufsize=1)