双击时运行Python脚本,但不会在IDLE

时间:2017-01-20 19:15:57

标签: python subprocess python-idle

所以我一直在尝试编写一个简短的脚本,自动提取Unity3D帮助页面(其中五个),以及Unity本身和TortoiseHG。由于webbrowser模块的行为不符合我的想法(在我的Win7盒子上),我一直在使用subprocess.run。

昨晚,我认为我最终解决了这个问题并让它做了我想要的事情,只是让它打开五个窗口而不是标签,如果Firefox还没有运行的话。与webbrowser.open相同的问题,去图。

但那并不是我在这里的原因。我在这里,因为当我用IDLE打开脚本试图修复那个问题时,我遇到了一个新问题:如果双击它,脚本会运行得很好,但是如果我尝试用F5运行它,我得到了

  Traceback (most recent call last):
  File "C:\Users\<me>\AppData\Local\Programs\Python\Python35-32\GameDevEnvironment.py", line 5, in <module>
    subprocess.run(r'start firefox -new-tab https://unity3d.com/learn/tutorials', shell=True)
AttributeError: 'module' object has no attribute 'run'

我的完整代码:

import os
import subprocess
#import time

subprocess.run(r'start firefox -new-tab https://unity3d.com/learn/tutorials', shell=True)

#time.sleep(5)

subprocess.run(r'start firefox -new-tab https://answers.unity3d.com', shell=True)

subprocess.run(r'start firefox -new-tab https://unity3d.com/learn/tutorials/topics/scripting', shell=True)

subprocess.run(r'start firefox -new-tab https://docs.unity3d.com/Manual/index.html', shell=True)

subprocess.run(r'start firefox -new-tab https://docs.unity3d.com/ScriptReference/index.html', shell=True)

#os.startfile(r'C:\Program Files\Unity\Editor\Unity.exe')

#os.startfile(r'C:\Program Files\TortoiseHg\thgw.exe')

我打算尝试使用time.sleep方法让Firefox进程运行,这样它就不会为每个subprocess.run调用打开一个新窗口(如前所述,它们会打开标签,如果Firefox已经运行)。我在尝试解决新问题时对此进行了评论。

我已经尝试过:寻找可能导致混乱的.pyc文件。找不到。确保我的方法或类都不是以Python模块命名的 - 正如您所看到的,没有任何方法或类定义,除非Python有一个名为GameDevEnvironment.py的模块......我发现了很多问题在这里和其他地方的人有相反的问题,在IDLE中运行而不是双击等,但是找不到任何明显相关的东西...

感谢您的时间和帮助!

1 个答案:

答案 0 :(得分:0)

由于原始问题是两个部分,这里有两部分答案(两者都在评论中)。

我无法从IDLE运行脚本的原因是shell版本比我编写的代码旧。基本上,在Python 3.2中,Subprocess类并不存在。当我卸载Python32以确保我只能在Python35中打开时,问题就解决了。

导致这个问题的另一个问题是,如果还没有运行Firefox的实例,则subprocess.run()会打开几个Firefox窗口。解决方案是在第一次和第二次调用subprocess.run()之间添加time.sleep()。对我来说,8秒是一个很长的时间让进程开始并允许第一页部分加载,这使第二页加载更快。由于我的机器已经老了,我最终在每个标签之间进行了一次睡眠 - 它看起来更平滑,但它增加了20秒的过程;不是很优雅。

如果你在这里寻找一种方法来获得结果而不获得Selenium,我的建议是:获得Selenium。我很确定如果我刚下载并学习它,它会节省我的时间和挫折感。

完成的代码(由于我的帐户是新的,因此必须断开链接):

import os
import subprocess
import time

os.startfile(r'C:\Program Files\Mozilla Thunderbird\thunderbird.exe')

subprocess.run(r'start firefox -new-tab unity3d[breaking link]/learn/tutorials', shell=True)

time.sleep(8)

subprocess.run(r'start firefox -new-tab answers.unity3d[breaking link]', shell=True)

time.sleep(3)

subprocess.run(r'start firefox -new-tab unity3d[breaking link]/learn/tutorials/topics/scripting', shell=True)

time.sleep(3)

subprocess.run(r'start firefox -new-tab docs.unity3d[breaking link]/Manual/index.html', shell=True)

time.sleep(3)

subprocess.run(r'start firefox -new-tab docs.unity3d.[breaking link]/ScriptReference/index.html', shell=True)

time.sleep(3)

os.startfile(r'C:\Program Files\TortoiseHg\thgw.exe')

os.startfile(r'C:\Program Files\Unity\Editor\Unity.exe')