如何使用 Python 启动应用程序的实例?
我正在创建一个 Python 脚本,它执行一系列任务,其中一个任务是启动并打开 Excel 实例。 在我的脚本中实现这一目标的理想方法是什么?
I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
虽然
Popen
答案对于一般情况来说是合理的,但如果您想用它做一些有用的事情,我会推荐win32api
对于这种特定情况:它是这样的:
摘自邮件列表帖子,但有很多周围的例子。
While the
Popen
answers are reasonable for the general case, I would recommendwin32api
for this specific case, if you want to do something useful with it:It goes something like this:
Taken from a mailing list post but there are plenty of examples around.
或者
(假设它在路径中,并且您在 Windows 上)
并且在 Windows 上,只需
start
也可以 - 如果它已经是关联的扩展名(如 xls 那样)or
(presuming it's in the path, and you're on windows)
and also on Windows, just
start <filename>
works, too - if it's an associated extension already (as xls would be)subprocess 模块旨在替换其他几个较旧的模块和函数,例如:
。
The subprocess module intends to replace several other, older modules and functions, such as:
.
我喜欢 popen2,因为它能够监控进程。
https://docs.python.org/2/library/popen2.html
编辑:请注意,调用
wait()
将阻塞,直到进程返回。 根据您的脚本,这可能不是您想要的行为。I like
popen2
for the ability to monitor the process.https://docs.python.org/2/library/popen2.html
EDIT: be aware that calling
wait()
will block until the process returns. Depending on your script, this may not be your desired behavior.正如其他人所说,我建议使用 os.system。 如果有人正在寻找 Mac 兼容的解决方案,这里有一个示例:
As others have stated, I would suggest os.system. In case anyone is looking for a Mac-compatible solution, here is an example:
os.system("打开文件.xls")
os.system("open file.xls")
我喜欢 os.startfile("path to file") 因为它打开文件就像双击打开一样。
我发现使用 os.system("start excel filename") 可以像从网络打开文件一样打开它,并且您必须启用编辑。
I like
os.startfile("path to file")
as it opens the file as if you've double clicked to open.I found that with
os.system("start excel filename")
it opened it like a file opened from the web and you had to enable editing.