【问题标题】:Python script to check dir not working用于检查目录的 Python 脚本不起作用
【发布时间】:2016-10-04 13:36:05
【问题描述】:

我一度被我的脚本卡住了。脚本是这样的

import subprocess
import os
def Windows():
    SW_MINIMIZE = 6
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW
    info.wShowWindow = SW_MINIMIZE
    print(os.path.isdir("C:\Program Files (x86)"))
    while True:
        try:
            subprocess.Popen(r'C:\Program Files (x86)\Mozilla   Firefox\firefox.exe', startupinfo=info)
        except WindowsError:
            subprocess.Popen(r'C:\Program Files   (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
    else:
        try:
            subprocess.Popen(r'C:\Program Files\Mozilla Firefox\firefox.exe', startupinfo=info)
        except WindowsError:
            subprocess.Popen(r'C:\Program Files\Google\Chrome\Application\chrome.exe', startupinfo=info)  

我要做的是检查计算机是 64 位还是 32 位(因为我想使用 subprocess 打开没有窗口的浏览器。)以找到浏览器 chromefirefox,具体取决于用户拥有哪一个(我假设他们拥有其中任何一个)。由于 chrome 和 firefox 的路径在 64 位和 32 位计算机(程序文件和程序文件(x84))中有所不同,我想出了这个脚本来检测 x86 文件夹是否存在。如果是,它将继续在文件夹中搜索浏览器。但是,如果不是,它假定它是 32 位并搜索 Program Files 文件夹并在该文件夹中搜索浏览器。 但是,当我运行脚本时出现此错误

Traceback (most recent call last):
  File "C:\Users\Charchit\Desktop\via.py", line 29, in <module>
    Windows()
  File "C:\Users\Charchit\Desktop\via.py", line 13, in Windows
    subprocess.Popen(r'C:\Program Files    (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
  File "C:\Python27\lib\subprocess.py", line 710, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

但是,在我的脚本中,它甚至不应该转到 while True 部分,因为我有一个 32 位系统并且 x86 文件夹不存在!

【问题讨论】:

  • @cxw 什么?没看懂
  • 嗯,'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe' 存在吗?
  • @MorganThrapp 不,它不存在,因为我有一个 32 位设备
  • ...lol...您应该从操作系统平台检查platform.machine().endswith('64') 开始,而不是根据文件路径检查平台...如果我只是通过模仿它的文件夹名...?

标签: python python-2.7 subprocess


【解决方案1】:

您实际上并没有检查os.path.isdir("C:\Program Files (x86)")。你只是在打印它。

代替

print(os.path.isdir("C:\Program Files (x86)"))
while True:

你需要做的

if os.path.isdir(r"C:\Program Files (x86)"):

旁注:

chrome 和 firefox 传统上都将自己置于路径上,因此您很有可能只做 subprocess.Popen('firefox.exe') / subprocess.Popen('chrome.exe')

【讨论】:

  • 谢谢你成功了,(我犯了这样的错误真是太愚蠢了)
【解决方案2】:

为了创建路径,请使用不会弄乱路径的内置 python 函数

if os.path.exists(os.path.join('C:', os.path.sep(), 'Program Files')):
   # do your stuff

【讨论】:

  • 这是真的,但这不是 OP 的问题。 \P 不是有效的转义,所以你不需要这样做。
猜你喜欢
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
相关资源
最近更新 更多