一名开发者在使用 Adobe Air2 NativeProcess API 试图从 Javascript 中启动一个 Python 脚本,但是在运行时遇到问题。他遵循了 Adobe AIR API Reference for HTML Developers 中的示例代码,但仍然无法成功启动 Python 脚本。
2. 解决方案
为了解决这个问题,开发者对 Python 脚本和 HTML 文件进行了修改。以下是修改后的代码:
HTML 文件:
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="AIRAliases.js"></script>
<script type="text/javascript">
var process;
function launchProcess()
{
if(air.NativeProcess.isSupported)
{
air.trace("NativeProcess supported.");
setupAndLaunch();
}
else
{
air.trace("NativeProcess not supported.");
}
}
function setupAndLaunch()
{
var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
var file = air.File.applicationDirectory.resolvePath("test.py");
nativeProcessStartupInfo.executable = file;
var processArgs = new air.Vector["<String>"]();
processArgs.push("foo");
nativeProcessStartupInfo.arguments = processArgs;
process = new air.NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
process.addEventListener(air.NativeProcessExitEvent.EXIT, onExit);
process.addEventListener(air.IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
process.addEventListener(air.IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
}
function onOutputData()
{
air.trace("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable));
}
function onErrorData(event)
{
air.trace("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable));
}
function onExit(event)
{
air.trace("Process exited with ", event.exitCode);
}
function onIOError(event)
{
air.trace(event.toString());
}
</script>
</head>
<body onload="launchProcess()">
</body>
</html>
Python 文件:
#! /usr/bin/env python2.5
# -*- coding: utf-8 -*-
import sys
import os
def convert(args):
path = os.path.expanduser('~') + "/Desktop/"
myFile = open(path + args, 'w')
myFile.write('Hello World\n')
myFile.close()
sys.stdout.write("Python Done")
if __name__ == "__main__":
convert(sys.argv[1])
关键修改点:
-
Python 文件:
- 将
print "Enter user name"
修改为print "Enter user name\n"
,使 Python 脚本能够正确读取用户输入。 - 将
sys.stdout.write("hello," + line)
修改为sys.stdout.write("hello, " + line)
,使 Python 脚本能够正确输出结果。 - 在 Python 脚本的开头添加
import sys
和import os
以导入必要的库。
- 将
-
HTML 文件:
- 在
var file = air.File.applicationDirectory.resolvePath("test.py");
中将test.py
替换为修改后的 Python 文件的名称。
- 在