【问题标题】:How to use python in windows to open javascript, have it interpreted by WScript, and pass it the command line arguments如何在windows中使用python打开javascript,由WScript解释,并传递命令行参数
【发布时间】:2010-10-20 13:48:19
【问题描述】:

我有一个格式保存文件的路径和命令行参数,当它们在 Windows 中打开时传递给这些文件。

例如,我可能有一个 javascript 文件的路径和一个传递它的命令行参数列表,在这种情况下,我想以与 os.startfile 相同的方式打开 javascript 文件并将其传递给命令行参数 - 由于参数保存为字符串,我想将其作为字符串传递,但如果需要,我也可以将其作为列表传递。

我不太确定我应该为此使用什么,因为 .js 不是可执行文件,因此会在 Popen 中引发错误,而 startfile 仅将动词作为其第二个命令。

此问题可以扩展到需要打开的任意数量的文件扩展名,并传递命令行参数,但在打开时将由真正的可执行文件解释。

【问题讨论】:

  • 您希望.js 文件如何在程序外的窗口中打开?
  • 我希望 Windows 中的默认解释器 WScript.exe 或 Cscript.exe 打开一个 .js 文件,这就是我调用 open 动词时发生的情况,例如通过双击文件在文件系统中。显然,某处需要知道解释器是什么,但我更愿意使用更高级别的解决方案,而不是实现“某处某处”。例如,如果我打开一个 .py 程序并从 WScript 传递一个命令行参数,我可以这样做,而不必知道 python.exe 需要打开 .py 扩展名,因为 Wscript 会为我处理这些。跨度>

标签: python windows process popen


【解决方案1】:

如果 windows 已注册 .js 扩展名以使用 wscript 打开,您可以这样做,将决定权留给 windows shell。

您可以只使用os.system() 来执行与在命令提示符下键入时相同的操作,例如:

import os
os.system('example.js arg1 arg2')

您也可以使用start 命令:

os.system('start example.js arg1 arg2') 

如果你需要更多的权力,例如为了得到结果,你可以使用subprocess.Popen(),但一定要使用shell=True(这样shell可以调用正确的应用程序):

from subprocess import Popen
p = Popen('example.js arg1 arg2', shell=True)
# you can also do pass the filename and arguments separately:
# p = Popen(['example.js', 'arg1', 'arg2'], shell=True)
stdoutdata, stderrdata = p.communicate()

(虽然这可能需要 cscript 而不是 wscript)

如果 Windows 没有任何默认应用程序来打开文件(或者如果它不是您想要的),那么您当然是靠自己...

【讨论】:

    猜你喜欢
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2020-08-27
    • 2016-02-22
    • 1970-01-01
    • 2016-10-09
    • 2019-07-16
    相关资源
    最近更新 更多