标签归档:windows

在Windows 7上添加Python路径

问题:在Windows 7上添加Python路径

我一直在尝试在Windows 7上将Python路径添加到命令行中,但是无论我尝试哪种方法,似乎都没有任何效果。我使用了该set命令,尝试通过“编辑环境”变量提示符等添加它。

此外,如果我在命令行上运行set命令,它将列出此内容

python = c:\python27

但是它仍然无法识别Python命令。

阅读文档以及其他各种资源似乎无济于事。

编辑:为了进一步说明,我在编辑环境提示中将Python可执行文件的路径附加到PATH。似乎不起作用。

I’ve been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I’ve used the set command, I’ve tried adding it through the Edit Environment variables prompt etc.

Further more if I run the set command on the command line it lists this

python = c:\python27

Yet it still doesn’t recognize the Python command.

Reading the documentation, and various other sources hasn’t seemed to help.

Edit: Just to clarify further, I’ve appended the path of the Python executable to PATH in edit environment prompt. Doesn’t seem to work.


回答 0

  1. 按住Win并按Pause
  2. 单击高级系统设置。
  3. 单击环境变量。
  4. 追加;C:\python27Path变量。
  5. 重新启动命令提示符。
  1. Hold Win and press Pause.
  2. Click Advanced System Settings.
  3. Click Environment Variables.
  4. Append ;C:\python27 to the Path variable.
  5. Restart Command Prompt.

回答 1

在Windows中设置环境变量时,我在很多情况下都出错了。我认为我应该在这里分享我过去的一些错误,希望对别人有所帮助。(这些适用于所有环境变量,不仅适用于设置Python路径)

当心这些可能的错误:

  1. 杀死并重新打开您的Shell窗口:对环境变量进行更改后,您必须重新启动要对其进行测试的窗口。
  2. 设置变量时没有空间。请确保您添加;C:\Python27无任何空格。(通常C:\SomeOther; C:\Python27在分号后尝试使用空格(␣)是不正确的。)
  3. 阐明完整路径时,请使用向后斜线。尝试时会看到正斜杠,echo $PATH但只有反斜杠对我有用。
  4. 不要添加最后的反斜杠。只有C:\Python27C:\Python27\

希望这对某人有帮助。

When setting Environmental Variables in Windows, I have gone wrong on many, many occasions. I thought I should share a few of my past mistakes here hoping that it might help someone. (These apply to all Environmental Variables, not just when setting Python Path)

Watch out for these possible mistakes:

  1. Kill and reopen your shell window: Once you make a change to the ENVIRONMENTAL Variables, you have to restart the window you are testing it on.
  2. NO SPACES when setting the Variables. Make sure that you are adding the ;C:\Python27 WITHOUT any spaces. (It is common to try C:\SomeOther; C:\Python27 That space (␣) after the semicolon is not okay.)
  3. USE A BACKWARD SLASH when spelling out your full path. You will see forward slashes when you try echo $PATH but only backward slashes have worked for me.
  4. DO NOT ADD a final backslash. Only C:\Python27 NOT C:\Python27\

Hope this helps someone.


回答 2

以管理员权限打开cmd .exe(右键单击应用程序)。然后输入:

setx路径“%path%; C:\ Python27;”

请记住以分号结尾,并且不要包含斜杠。

Open cmd.exe with administrator privileges (right click on app). Then type:

setx path “%path%;C:\Python27;”

Remember to end with a semi-colon and don’t include a trailing slash.


回答 3

我已经很久没有这个问题了。我以各种方式将其添加到我的路径中,但这终于对我有用:

  1. 右键单击“我的电脑”
  2. 点击“属性”
  3. 点击侧面板中的“高级系统设置”
  4. 点击“环境变量”
  5. 点击系统变量下面的“新建”
  6. 输入名称pythonexe(或您想要的任何名称
  7. 在值输入路径你的Python(例如:C:\Python32\
  8. 现在,编辑Path变量(在系统部分),然后添加%pythonexe%;到已经存在的末尾

IDK为什么这样做有效,但对我有用。

然后尝试在命令行中输入“ python”,它应该可以工作!


编辑:

最近,我一直在使用该程序,它似乎运行良好。还有一个看起来也不错,尽管我从未尝试过。

I’ve had a problem with this for a LONG time. I added it to my path in every way I could think of but here’s what finally worked for me:

  1. Right click on “My computer”
  2. Click “Properties”
  3. Click “Advanced system settings” in the side panel
  4. Click “Environment Variables”
  5. Click the “New” below system variables
  6. in name enter pythonexe (or anything you want)
  7. in value enter the path to your python (example: C:\Python32\)
  8. Now edit the Path variable (in the system part) and add %pythonexe%; to the end of what’s already there

IDK why this works but it did for me.

then try typing “python” into your command line and it should work!


Edit:

Lately I’ve been using this program which seems to work pretty well. There’s also this one which looks pretty good too, although I’ve never tried it.


回答 4

尝试将此python.bat文件添加到System32文件夹,然后在键入时命令行将运行pythonpython

python.bat

@C:\Python27\python.exe %*

资源:

https://github.com/KartikTalwar/dotfiles/blob/master/bat/python.bat

Try adding this python.bat file to System32 folder and the command line will now run python when you type in python

python.bat

@C:\Python27\python.exe %*

Source:

https://github.com/KartikTalwar/dotfiles/blob/master/bat/python.bat


回答 5

您可以使用命令从当前cmd窗口设置路径PATH =。那只会为当前的cmd实例添加它。如果要永久添加,则应将其添加到系统变量。(计算机>高级系统设置>环境变量)

您将转到您的cmd实例,然后放入PATH=C:/Python27/;%PATH%

You can set the path from the current cmd window using the PATH = command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables)

You would goto your cmd instance, and put in PATH=C:/Python27/;%PATH%.


回答 6

确保您没有在新目录之前添加空格。

好:旧;旧;旧;新

不好:老;老;老;新

Make sure you don’t add a space before the new directory.

Good: old;old;old;new

Bad: old;old;old; new


回答 7

Python带有一个小型工具,可以执行此操作。从命令行运行:

c:\python27\tools\scripts\win_add2path.py

确保关闭命令窗口(使用exit或关闭按钮),然后再次打开它。

Python comes with a small utility that does just this. From the command line run:

c:\python27\tools\scripts\win_add2path.py

Make sure you close the command window (with exit or the close button) and open it again.


回答 8

以下程序将python可执行路径和subdir脚本(例如pip和easy_install的安装位置)添加到您的环境中。它从绑定.py扩展名的注册表项中找到python可执行文件的路径。它将删除您环境中的旧python路径。也适用于XP(可能还有Vista)。它仅使用基本Windows安装程序随附的模块。

# coding: utf-8

import sys
import os
import time
import _winreg
import ctypes

def find_python():
    """
    retrieves the commandline for .py extensions from the registry
    """
    hKey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
                           r'Python.File\shell\open\command')
    # get the default value
    value, typ = _winreg.QueryValueEx (hKey, None)
    program = value.split('"')[1]
    if not program.lower().endswith(r'\python.exe'):
        return None
    return os.path.dirname(program)

def extend_path(pypath, remove=False, verbose=0, remove_old=True,
                script=False):
    """
    extend(pypath) adds pypath to the PATH env. variable as defined in the
    registry, and then notifies applications (e.g. the desktop) of this change.
    !!! Already opened DOS-Command prompts are not updated. !!!
    Newly opened prompts will have the new path (inherited from the 
    updated windows explorer desktop)
    options:
    remove (default unset), remove from PATH instead of extend PATH
    remove_old (default set), removes any (old) python paths first
    script (default unset), try to add/remove the Scripts subdirectory 
        of pypath (pip, easy_install) as well
    """
    _sd = 'Scripts' # scripts subdir
    hKey = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE,
               r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
               0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE)

    value, typ = _winreg.QueryValueEx (hKey, "PATH")
    vals = value.split(';')
    assert isinstance(vals, list)
    if not remove and remove_old:
        new_vals = []
        for v in vals:
            pyexe = os.path.join(v, 'python.exe')
            if v != pypath and os.path.exists(pyexe):
                if verbose > 0:
                    print 'removing from PATH:', v
                continue
            if script and v != os.path.join(pypath, _sd) and \
               os.path.exists(v.replace(_sd, pyexe)):
                if verbose > 0:
                    print 'removing from PATH:', v
                continue
            new_vals.append(v)
        vals = new_vals
    if remove:
        try:
            vals.remove(pypath)
        except ValueError:
            if verbose > 0:
                print 'path element', pypath, 'not found'
            return
        if script:
            try:
                vals.remove(os.path.join(pypath, _sd))
            except ValueError:
                pass
            print 'removing from PATH:', pypath
    else:
        if pypath in vals:
            if verbose > 0:
                print 'path element', pypath, 'already in PATH'
            return
        vals.append(pypath)
        if verbose > 1:
            print 'adding to PATH:', pypath
        if script:
            if not pypath + '\\Scripts' in vals:
                vals.append(pypath + '\\Scripts')
            if verbose > 1:
                print 'adding to PATH:', pypath + '\\Scripts'
    _winreg.SetValueEx(hKey, "PATH", 0, typ, ';'.join(vals) )
    _winreg.SetValueEx(hKey, "OLDPATH", 0, typ, value )
    _winreg.FlushKey(hKey)
    # notify other programs
    SendMessage = ctypes.windll.user32.SendMessageW
    HWND_BROADCAST = 0xFFFF
    WM_SETTINGCHANGE = 0x1A
    SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment')
    if verbose > 1:
        print 'Do not forget to restart any command prompts'

if __name__ == '__main__':
    remove = '--remove' in sys.argv
    script = '--noscripts' not in sys.argv
    extend_path(find_python(), verbose=2, remove=remove, script=script)

The following program will add the python executable path and the subdir Scripts (which is where e.g. pip and easy_install are installed) to your environment. It finds the path to the python executable from the registry key binding the .py extension. It will remove old python paths in your environment. Works with XP (and probably Vista) as well. It only uses modules that come with the basic windows installer.

# coding: utf-8

import sys
import os
import time
import _winreg
import ctypes

def find_python():
    """
    retrieves the commandline for .py extensions from the registry
    """
    hKey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
                           r'Python.File\shell\open\command')
    # get the default value
    value, typ = _winreg.QueryValueEx (hKey, None)
    program = value.split('"')[1]
    if not program.lower().endswith(r'\python.exe'):
        return None
    return os.path.dirname(program)

def extend_path(pypath, remove=False, verbose=0, remove_old=True,
                script=False):
    """
    extend(pypath) adds pypath to the PATH env. variable as defined in the
    registry, and then notifies applications (e.g. the desktop) of this change.
    !!! Already opened DOS-Command prompts are not updated. !!!
    Newly opened prompts will have the new path (inherited from the 
    updated windows explorer desktop)
    options:
    remove (default unset), remove from PATH instead of extend PATH
    remove_old (default set), removes any (old) python paths first
    script (default unset), try to add/remove the Scripts subdirectory 
        of pypath (pip, easy_install) as well
    """
    _sd = 'Scripts' # scripts subdir
    hKey = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE,
               r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
               0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE)

    value, typ = _winreg.QueryValueEx (hKey, "PATH")
    vals = value.split(';')
    assert isinstance(vals, list)
    if not remove and remove_old:
        new_vals = []
        for v in vals:
            pyexe = os.path.join(v, 'python.exe')
            if v != pypath and os.path.exists(pyexe):
                if verbose > 0:
                    print 'removing from PATH:', v
                continue
            if script and v != os.path.join(pypath, _sd) and \
               os.path.exists(v.replace(_sd, pyexe)):
                if verbose > 0:
                    print 'removing from PATH:', v
                continue
            new_vals.append(v)
        vals = new_vals
    if remove:
        try:
            vals.remove(pypath)
        except ValueError:
            if verbose > 0:
                print 'path element', pypath, 'not found'
            return
        if script:
            try:
                vals.remove(os.path.join(pypath, _sd))
            except ValueError:
                pass
            print 'removing from PATH:', pypath
    else:
        if pypath in vals:
            if verbose > 0:
                print 'path element', pypath, 'already in PATH'
            return
        vals.append(pypath)
        if verbose > 1:
            print 'adding to PATH:', pypath
        if script:
            if not pypath + '\\Scripts' in vals:
                vals.append(pypath + '\\Scripts')
            if verbose > 1:
                print 'adding to PATH:', pypath + '\\Scripts'
    _winreg.SetValueEx(hKey, "PATH", 0, typ, ';'.join(vals) )
    _winreg.SetValueEx(hKey, "OLDPATH", 0, typ, value )
    _winreg.FlushKey(hKey)
    # notify other programs
    SendMessage = ctypes.windll.user32.SendMessageW
    HWND_BROADCAST = 0xFFFF
    WM_SETTINGCHANGE = 0x1A
    SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment')
    if verbose > 1:
        print 'Do not forget to restart any command prompts'

if __name__ == '__main__':
    remove = '--remove' in sys.argv
    script = '--noscripts' not in sys.argv
    extend_path(find_python(), verbose=2, remove=remove, script=script)

回答 9

我知道这篇文章很旧,但我想补充一点,该解决方案假设使用admin privs。如果您没有这些,可以:

转到控制面板,键入路径(此为Windows 7,现在在搜索框中),然后单击“为您的帐户编辑环境变量”。现在,您将看到环境变量对话框,其顶部为“用户变量”,而其下方为“系统变量”。

您可以作为用户单击顶部的“新建”按钮并添加:

变量名称:PATH
变量值:C:\ Python27

(任何地方都没有空格),然后单击“确定”。重新启动命令提示符后,User变量中的所有PATH都将附加到系统路径的末尾。它不会以任何其他方式替换PATH。

如果要设置特定的完整路径,最好创建一个像这样的批处理文件:

@echo off
PATH C:\User\Me\Programs\mingw\bin;C:\User\Me\Programs;C:\Windows\system32
title Compiler Environment - %Username%@%Computername%
cmd

将其命名为“ compiler.bat”或双击以启动它。或链接到它。或固定等等…

I know this post is old but I’d like to add that the solutions assume admin privs. If you don’t have those you can:

Go to control panel, type path (this is Windows 7 now so that’s in the Search box) and click “Edit Environment variables for your account”. You’ll now see the Environment Variable dialog with “User variables” on the top and “System variables” below.

You can, as a user, click the top “New” button and add:

Variable name: PATH
Variable value: C:\Python27

(no spaces anywhere) and click OK. Once your command prompt is restarted, any PATH in the User variables is appended to the end of the System Path. It doesn’t replace the PATH in any other way.

If you want a specific full path set up, you’re better off creating a batch file like this little one:

@echo off
PATH C:\User\Me\Programs\mingw\bin;C:\User\Me\Programs;C:\Windows\system32
title Compiler Environment - %Username%@%Computername%
cmd

Call it “compiler.bat” or whatever and double click to start it. Or link to it. Or pin it etc…


回答 10

您需要在系统变量中进行更改
-右键单击“我的电脑”
-单击“属性”
-单击侧面板中的“高级系统设置”
-单击环境变量-您将分为两部分变量和系统变量
-在系统变量部分下搜索变量’Path’单击编辑并添加
"C:\Python27;"(不带引号)将其保存
-现在打开命令行类型’path’ 并按Enter,您将看到路径变量已被修改
-现在输入python --version您将看到python版本

完成了

You need to make changes in your system variable
— Right click on “My computer”
— Click “Properties”
— Click “Advanced system settings” in the side panel
— Click on Environment Variable — You will two sections of user variable and system variable
— Under system variable section search for the variable ‘Path’ click on edit and add
"C:\Python27;" (without quotes) save it
— Now open command line type ‘path’ hit enter you will see path variable has been modified
— Now type python --version you will see the python version

And it is done


回答 11

对于尝试使用Python 3.3+实现此目标的任何人,Windows安装程序现在都提供了一个将python.exe添加到系统搜索路径的选项。在docs中阅读更多内容。

For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.


回答 12

使用Windows环境变量始终是一种可怕的经历。最近,我发现了一个令人称奇的工具,称为Rapid Environment Editor,它提供了非常简单的GUI来管理它们。

如果您使用Chocolatey,则可以使用安装它choco install rapidee。否则,请访问http://www.rapidee.com/cn/download

重新阅读此内容,听起来像是有偿的,但是我发誓我不是!一段时间以来,它一直是我工具箱中最有用的实用程序之一,但令我惊讶的是似乎没人知道它。

Working with Windows environment variables is always a horrible experience. Recently, I found an amazing tool called Rapid Environment Editor, which gives an awesomely simple GUI for managing them.

If you use chocolatey, you can install it using choco install rapidee. Otherwise, take a look at http://www.rapidee.com/en/download

Re-reading this, it sounds like a paid shill, but I swear I’m not! It’s just been one of the most useful utilities in my toolkit for a while and I’m surprised no one seems to know about it.


回答 13

如果Python与其他程序一起安装,例如我的ArcGIS 10.1,则还必须在环境变量中包含指向python.exe路径的所有其他文件夹。

所以我的环境变量看起来像这样:

系统变量>路径>添加 ;C:\Python27\ArcGIS10.1

If Python was installed with another program, such as ArcGIS 10.1 in my case, then you also must include any extra folders that path to the python.exe in your Environment Variables.

So my Environment Variables looks like this:

System variables > Path > add ;C:\Python27\ArcGIS10.1


回答 14

这个问题已经很老了,但是我遇到了一个类似的问题,这里没有列出我的特定解决方案:

确保您的PATH中没有不存在的文件夹。

就我而言,我有一堆默认文件夹(Windows,Powershell,Sql Server等),然后是C:\bin我通常使用的自定义,然后进行了其他各种调整,例如c:\python17等等。事实证明,cmd处理器发现c:\bin没有不存在,然后停止处理其余变量。

另外,我不知道如果没有PATH manager,我是否会注意到这一点。它很好地强调了该项目无效的事实。

This question is pretty old, but I just ran into a similar problem and my particular solution wasn’t listed here:

Make sure you don’t have a folder in your PATH that doesn’t exist.

In my case, I had a bunch of default folders (Windows, Powershell, Sql Server, etc) and then a custom C:\bin that I typically use, and then various other tweaks like c:\python17, etc. It turns out that the cmd processor was finding that c:\bin didn’t exist and then stopped processing the rest of the variable.

Also, I don’t know that I ever would have noticed this without PATH manager. It nicely highlighted the fact that that item was invalid.


回答 15

我刚刚使用选项“将python添加到PATH”在Windows 7上安装了Python 3.3。

在PATH变量中,安装程序会自动添加最后一个反斜杠C:\Python33\ ,因此在命令提示符下不起作用(我尝试多次关闭/打开提示符)

我删除了最后的反斜杠,然后它起作用了:C:\Python33

感谢Ram Narasimhan给您的提示4!

I just installed Python 3.3 on Windows 7 using the option “add python to PATH”.

In PATH variable, the installer automatically added a final backslash: C:\Python33\ and so it did not work on command prompt (i tried closing/opening the prompt several times)

I removed the final backslash and then it worked: C:\Python33

Thanks Ram Narasimhan for your tip #4 !


回答 16

我使用cmd在Win7 64位下组织了这样的python环境变量。

PYTHONPATH通过Windows的环境变量菜单设置变量,并将其添加%PYTHONPATH%PATH变量中:

...;%PYTHONPATH%

cmd shell将变量正确扩展为:

C:\>echo %PYTHONPATH%
C:\python27;c:\python27\lib;C:\python27\scripts

不要忘记在更改PATH之后重新启动cmd shell。

I organized my python environment variable like this under Win7 64-bit using cmd.

I set the variable PYTHONPATH via environment variable menue of windows and added %PYTHONPATH% to the PATH variable:

...;%PYTHONPATH%

The cmd shell expands the variable correctly to this:

C:\>echo %PYTHONPATH%
C:\python27;c:\python27\lib;C:\python27\scripts

Do not forget to restart cmd shell after changing PATH.


回答 17

将其写在命令提示符上:

set Path=%path%

用Python文件夹示例的路径替换%path%:

set Path=C:/Python27

write that on your Command Prompt:

set Path=%path%

Replace %path% by the Path of your Python Folder Example:

set Path=C:/Python27

回答 18

如果您对设置python的路径感到沮丧,只需下载新版本的python并卸载旧版本的python,并在安装新版本时询问是否设置路径标记并安装

这是最好的方法

If you have got frustrated by setting the path for the python just download the new version of python uninstall the older version of the python and while installing the new version it will ask whether to set path mark that and install

its the best way


如何获取按python创建日期排序的目录列表?

问题:如何获取按python创建日期排序的目录列表?

获取目录中所有文件的列表的最佳方法是什么,按日期[创建| 修改],在Windows机器上使用python?

What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?


回答 0

更新dirpath在Python 3中按修改日期对条目进行排序:

import os
from pathlib import Path

paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)

(在这里输入@Pygirl的答案以提高知名度)

如果您已经有了一个文件名列表files,则可以在Windows上按创建时间对其进行排序:

files.sort(key=os.path.getctime)

例如,您可以使用@Jay的答案中glob所示的文件列表。


老答案 这里有一个更详细的版本@Greg Hewgill的答案。这是最符合问题要求的。它区分了创建日期和修改日期(至少在Windows上如此)。

#!/usr/bin/env python
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time

# path to the directory (relative or absolute)
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

# get all entries in the directory w/ stats
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)

# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
           for stat, path in entries if S_ISREG(stat[ST_MODE]))
#NOTE: on Windows `ST_CTIME` is a creation date 
#  but on Unix it could be something else
#NOTE: use `ST_MTIME` to sort by a modification date

for cdate, path in sorted(entries):
    print time.ctime(cdate), os.path.basename(path)

例:

$ python stat_creation_date.py
Thu Feb 11 13:31:07 2009 stat_creation_date.py

Update: to sort dirpath‘s entries by modification date in Python 3:

import os
from pathlib import Path

paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)

(put @Pygirl’s answer here for greater visibility)

If you already have a list of filenames files, then to sort it inplace by creation time on Windows:

files.sort(key=os.path.getctime)

The list of files you could get, for example, using glob as shown in @Jay’s answer.


old answer Here’s a more verbose version of @Greg Hewgill‘s answer. It is the most conforming to the question requirements. It makes a distinction between creation and modification dates (at least on Windows).

#!/usr/bin/env python
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time

# path to the directory (relative or absolute)
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

# get all entries in the directory w/ stats
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)

# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
           for stat, path in entries if S_ISREG(stat[ST_MODE]))
#NOTE: on Windows `ST_CTIME` is a creation date 
#  but on Unix it could be something else
#NOTE: use `ST_MTIME` to sort by a modification date

for cdate, path in sorted(entries):
    print time.ctime(cdate), os.path.basename(path)

Example:

$ python stat_creation_date.py
Thu Feb 11 13:31:07 2009 stat_creation_date.py

回答 1

过去,我是使用Python脚本来确定目录中最近更新的文件的方式:

import glob
import os

search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list 
# of files (presumably not including directories)  
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))

这应该可以根据文件mtime执行您想要的操作。

编辑:请注意,如果需要,也可以使用os.listdir()代替glob.glob()-我在原始代码中使用glob的原因是我想使用glob仅搜索具有特定集合的文件文件扩展名,glob()更适合。要使用listdir,结果如下所示:

import os

search_dir = "/mydir/"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))

I’ve done this in the past for a Python script to determine the last updated files in a directory:

import glob
import os

search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list 
# of files (presumably not including directories)  
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))

That should do what you’re looking for based on file mtime.

EDIT: Note that you can also use os.listdir() in place of glob.glob() if desired – the reason I used glob in my original code was that I was wanting to use glob to only search for files with a particular set of file extensions, which glob() was better suited to. To use listdir here’s what it would look like:

import os

search_dir = "/mydir/"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))

回答 2

有一个os.path.getmtime函数可以指定自epoch以来的秒数,并且应快于os.stat

import os 

os.chdir(directory)
sorted(filter(os.path.isfile, os.listdir('.')), key=os.path.getmtime)

There is an os.path.getmtime function that gives the number of seconds since the epoch and should be faster than os.stat.

import os 

os.chdir(directory)
sorted(filter(os.path.isfile, os.listdir('.')), key=os.path.getmtime)

回答 3

这是我的版本:

def getfiles(dirpath):
    a = [s for s in os.listdir(dirpath)
         if os.path.isfile(os.path.join(dirpath, s))]
    a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)))
    return a

首先,我们建立文件名列表。isfile()用于跳过目录;如果应包括目录,则可以省略。然后,我们使用修改日期作为关键字对列表进行排序。

Here’s my version:

def getfiles(dirpath):
    a = [s for s in os.listdir(dirpath)
         if os.path.isfile(os.path.join(dirpath, s))]
    a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)))
    return a

First, we build a list of the file names. isfile() is used to skip directories; it can be omitted if directories should be included. Then, we sort the list in-place, using the modify date as the key.


回答 4

这里是单线:

import os
import time
from pprint import pprint

pprint([(x[0], time.ctime(x[1].st_ctime)) for x in sorted([(fn, os.stat(fn)) for fn in os.listdir(".")], key = lambda x: x[1].st_ctime)])

这将调用os.listdir()以获得文件名列表,然后为每个文件名调用os.stat()以获得创建时间,然后根据创建时间进行排序。

请注意,此方法仅对每个文件调用os.stat()一次,这比对某种比较中的每个比较调用它更有效。

Here’s a one-liner:

import os
import time
from pprint import pprint

pprint([(x[0], time.ctime(x[1].st_ctime)) for x in sorted([(fn, os.stat(fn)) for fn in os.listdir(".")], key = lambda x: x[1].st_ctime)])

This calls os.listdir() to get a list of the filenames, then calls os.stat() for each one to get the creation time, then sorts against the creation time.

Note that this method only calls os.stat() once for each file, which will be more efficient than calling it for each comparison in a sort.


回答 5

不更改目录:

import os    

path = '/path/to/files/'
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)

print time_sorted_list

# if you want just the filenames sorted, simply remove the dir from each
sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]
print sorted_filename_list

Without changing directory:

import os    

path = '/path/to/files/'
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)

print time_sorted_list

# if you want just the filenames sorted, simply remove the dir from each
sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]
print sorted_filename_list

回答 6

在python 3.5+

from pathlib import Path
sorted(Path('.').iterdir(), key=lambda f: f.stat().st_mtime)

In python 3.5+

from pathlib import Path
sorted(Path('.').iterdir(), key=lambda f: f.stat().st_mtime)

回答 7

如果您想按日期顺序读取具有某些扩展名的文件,这是我使用不带过滤器的glob的答案(Python 3)。

dataset_path='/mydir/'   
files = glob.glob(dataset_path+"/morepath/*.extension")   
files.sort(key=os.path.getmtime)

Here’s my answer using glob without filter if you want to read files with a certain extension in date order (Python 3).

dataset_path='/mydir/'   
files = glob.glob(dataset_path+"/morepath/*.extension")   
files.sort(key=os.path.getmtime)

回答 8

# *** the shortest and best way ***
# getmtime --> sort by modified time
# getctime --> sort by created time

import glob,os

lst_files = glob.glob("*.txt")
lst_files.sort(key=os.path.getmtime)
print("\n".join(lst_files))
# *** the shortest and best way ***
# getmtime --> sort by modified time
# getctime --> sort by created time

import glob,os

lst_files = glob.glob("*.txt")
lst_files.sort(key=os.path.getmtime)
print("\n".join(lst_files))

回答 9

sorted(filter(os.path.isfile, os.listdir('.')), 
    key=lambda p: os.stat(p).st_mtime)

您可以使用os.walk('.').next()[-1]而不是进行过滤os.path.isfile,但这会在列表中留下os.stat无效的符号链接,从而使它们失败。

sorted(filter(os.path.isfile, os.listdir('.')), 
    key=lambda p: os.stat(p).st_mtime)

You could use os.walk('.').next()[-1] instead of filtering with os.path.isfile, but that leaves dead symlinks in the list, and os.stat will fail on them.


回答 10

from pathlib import Path
import os

sorted(Path('./').iterdir(), key=lambda t: t.stat().st_mtime)

要么

sorted(Path('./').iterdir(), key=os.path.getmtime)

要么

sorted(os.scandir('./'), key=lambda t: t.stat().st_mtime)

其中,m时间为修改时间。

from pathlib import Path
import os

sorted(Path('./').iterdir(), key=lambda t: t.stat().st_mtime)

or

sorted(Path('./').iterdir(), key=os.path.getmtime)

or

sorted(os.scandir('./'), key=lambda t: t.stat().st_mtime)

where m time is modified time.


回答 11

这是学习的基本步骤:

import os, stat, sys
import time

dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

listdir = os.listdir(dirpath)

for i in listdir:
    os.chdir(dirpath)
    data_001 = os.path.realpath(i)
    listdir_stat1 = os.stat(data_001)
    listdir_stat2 = ((os.stat(data_001), data_001))
    print time.ctime(listdir_stat1.st_ctime), data_001

this is a basic step for learn:

import os, stat, sys
import time

dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

listdir = os.listdir(dirpath)

for i in listdir:
    os.chdir(dirpath)
    data_001 = os.path.realpath(i)
    listdir_stat1 = os.stat(data_001)
    listdir_stat2 = ((os.stat(data_001), data_001))
    print time.ctime(listdir_stat1.st_ctime), data_001

回答 12

如果文件是到不存在文件的符号链接,则Alex Coventry的答案将产生异常,以下代码更正了该答案:

import time
import datetime
sorted(filter(os.path.isfile, os.listdir('.')), 
    key=lambda p: os.path.exists(p) and os.stat(p).st_mtime or time.mktime(datetime.now().timetuple())

如果文件不存在,则使用no​​w(),符号链接将位于列表的最后。

Alex Coventry’s answer will produce an exception if the file is a symlink to an unexistent file, the following code corrects that answer:

import time
import datetime
sorted(filter(os.path.isfile, os.listdir('.')), 
    key=lambda p: os.path.exists(p) and os.stat(p).st_mtime or time.mktime(datetime.now().timetuple())

When the file doesn’t exist, now() is used, and the symlink will go at the very end of the list.


回答 13

这是一条简单的几行,用于查找扩展并提供排序选项

def get_sorted_files(src_dir, regex_ext='*', sort_reverse=False): 
    files_to_evaluate = [os.path.join(src_dir, f) for f in os.listdir(src_dir) if re.search(r'.*\.({})$'.format(regex_ext), f)]
    files_to_evaluate.sort(key=os.path.getmtime, reverse=sort_reverse)
    return files_to_evaluate

Here is a simple couple lines that looks for extention as well as provides a sort option

def get_sorted_files(src_dir, regex_ext='*', sort_reverse=False): 
    files_to_evaluate = [os.path.join(src_dir, f) for f in os.listdir(src_dir) if re.search(r'.*\.({})$'.format(regex_ext), f)]
    files_to_evaluate.sort(key=os.path.getmtime, reverse=sort_reverse)
    return files_to_evaluate

回答 14

为了os.scandir确保完整性(比快2倍pathlib):

import os
sorted(os.scandir('/tmp/test'), key=lambda d: d.stat().st_mtime)

For completeness with os.scandir (2x faster over pathlib):

import os
sorted(os.scandir('/tmp/test'), key=lambda d: d.stat().st_mtime)

回答 15

这是我的版本:

import os

folder_path = r'D:\Movies\extra\new\dramas' # your path
os.chdir(folder_path) # make the path active
x = sorted(os.listdir(), key=os.path.getctime)  # sorted using creation time

folder = 0

for folder in range(len(x)):
    print(x[folder]) # print all the foldername inside the folder_path
    folder = +1

This was my version:

import os

folder_path = r'D:\Movies\extra\new\dramas' # your path
os.chdir(folder_path) # make the path active
x = sorted(os.listdir(), key=os.path.getctime)  # sorted using creation time

folder = 0

for folder in range(len(x)):
    print(x[folder]) # print all the foldername inside the folder_path
    folder = +1

回答 16

也许您应该使用shell命令。在Unix / Linux中,使用sort传递的find可能可以执行您想要的操作。

Maybe you should use shell commands. In Unix/Linux, find piped with sort will probably be able to do what you want.


我可以将Python Windows软件包安装到virtualenvs吗?

问题:我可以将Python Windows软件包安装到virtualenvs吗?

Virtualenv很棒:它可以让我保留许多不同的Python安装,这样就不会将不同项目的依赖项放在一起。

但是,如果要在以.exe安装程序打包的Windows上安装软件包,如何将其定向安装到virtualenv中?例如,我有pycuda-0.94rc.win32-py2.6.exe。当我运行它时,它会检查注册表,并仅找到一个要安装到我的virtualenv所基于的通用Python26中。

如何引导它安装到virtualenv中?

Virtualenv is great: it lets me keep a number of distinct Python installations so that different projects’ dependencies aren’t all thrown together into a common pile.

But if I want to install a package on Windows that’s packaged as a .exe installer, how can I direct it to install into the virtualenv? For example, I have pycuda-0.94rc.win32-py2.6.exe. When I run it, it examines the registry, and finds only one Python26 to install into, the common one that my virtualenv is based off of.

How can I direct it to install into the virtualenv?


回答 0

是的你可以。所有你需要的是

easy_install binary_installer_built_with_distutils.exe

惊讶吗 看起来用distutils制作的Windows二进制安装程序将.exe和.zip合并为一个.exe文件。将扩展名更改为.zip以查看它是有效的zip文件。在阅读我的问题的答案后,我发现了这一点。在哪里可以从Windows下载带有psycopg2的二进制鸡蛋?

更新

正如Tritium21在他今天的回答中指出的那样,您应该使用pip代替easy_install。Pip无法安装distutils创建的二进制软件包,但可以在新版本中安装二进制软件包 wheel格式的。您可以使用滚轮套件将旧格式转换为新格式,必须先安装。

Yes, you can. All you need is

easy_install binary_installer_built_with_distutils.exe

Surprised? It looks like binary installers for Windows made with distutils combine .exe with .zip into one .exe file. Change extension to .zip to see it’s a valid zip file. I discovered this after reading answers to my question Where can I download binary eggs with psycopg2 for Windows?

UPDATE

As noted by Tritium21 in his answer nowadays you should use pip instead of easy_install. Pip can’t install binary packages created by distutils but it can install binary packages in the new wheel format. You can convert from old format to the new one using wheel package, which you have to install first.


回答 1

我知道这是一个很老的问题,并且早于我要谈论的工具,但是对于Google而言,我认为提这个问题是个好主意。easy_install是python包装的败类。没有人愿意承认使用这种新的流行点子。同样,尽管玩注册表技巧对于非标准EXE安装程序最为有效(有人自己安装了安装程序而不是使用distutils,并正在检查注册表中的安装路径),但现在有一种更好的方法用于标准EXE安装程序。

pip install wheel
wheel convert INSTALLER.EXE
pip install NEW_FILE_CREATED_IN_LAST_STEP.whl

在本博文中最近引入的轮式是蛋形的替代品,起着相同的作用。pip(virtualenv中已安装的工具)也支持此格式。

如果由于某种原因pip install WHEELFILE不起作用,请尝试wheel install WHEELFILE

I know this is quite an old question, and predates the tools I am about to talk about, but for the sake of Google, I think it is a good idea to mention it. easy_install is the black sheep of python packaging. No one wants to admit using it with the new hotness of pip around. Also, while playing registry tricks will work best for non-standard EXE installers (someone built the installer themselves instead of using distutils, and is checking the registry for the installation path), there is now a Better Way(c) for standard EXE installers.

pip install wheel
wheel convert INSTALLER.EXE
pip install NEW_FILE_CREATED_IN_LAST_STEP.whl

The wheel format, introduced recently as of this post, is the replacement for the egg format, filling much the same role. This format is also supported by pip (a tool already installed in your virtualenv).

if for some reason pip install WHEELFILE does not work, try wheel install WHEELFILE


回答 2

我最终修改了一个脚本(http://effbot.org/zone/python-register.htm)以在注册表中注册Python安装。我可以选择Python 作为注册表中 Python,运行Windows安装程序,然后重新设置注册表:

# -*- encoding: utf-8 -*-
#
# script to register Python 2.0 or later for use with win32all
# and other extensions that require Python registry settings
#
# Adapted by Ned Batchelder from a script
# written by Joakim Löw for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_LOCAL_MACHINE, regpath)
    except EnvironmentError:
        try:
            reg = CreateKey(HKEY_LOCAL_MACHINE, regpath)
        except Exception, e:
            print "*** Unable to register: %s" % e
            return

    SetValue(reg, installkey, REG_SZ, installpath)
    SetValue(reg, pythonkey, REG_SZ, pythonpath)
    CloseKey(reg)
    print "--- Python %s at %s is now registered!" % (version, installpath)

if __name__ == "__main__":
    RegisterPy()

使用您要注册的Python运行此脚本,它将被输入到注册表中。请注意,在Windows 7和Vista上,您需要具有管理员权限。

I ended up adapting a script (http://effbot.org/zone/python-register.htm) to register a Python installation in the registry. I can pick the Python to be the Python in the registry, run the Windows installer, then set the registry back:

# -*- encoding: utf-8 -*-
#
# script to register Python 2.0 or later for use with win32all
# and other extensions that require Python registry settings
#
# Adapted by Ned Batchelder from a script
# written by Joakim Löw for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_LOCAL_MACHINE, regpath)
    except EnvironmentError:
        try:
            reg = CreateKey(HKEY_LOCAL_MACHINE, regpath)
        except Exception, e:
            print "*** Unable to register: %s" % e
            return

    SetValue(reg, installkey, REG_SZ, installpath)
    SetValue(reg, pythonkey, REG_SZ, pythonpath)
    CloseKey(reg)
    print "--- Python %s at %s is now registered!" % (version, installpath)

if __name__ == "__main__":
    RegisterPy()

Run this script with the Python you want to be registered, and it will be entered into the registry. Note that on Windows 7 and Vista, you’ll need Administrator privileges.


回答 3

easy_install能够安装.exe软件包,只要它们是使用distutils的bdist_wininst目标构建的,该目标涵盖了许多流行的软件包。但是,还有许多其他方面不是(wxPython是我一直在努力的一种)

easy_install is able to install .exe packages as long as they were built using distutils’ bdist_wininst target, which covers many popular packages. However, there are many others that aren’t (wxPython is one that I’ve struggled with)


回答 4

您可以使用环境的easy_install来安装PyCUDA。

dev-env-path/bin/easy_install pycuda

它将为您提供相同的0.94rc版本。

在Windows上,easy_install.exe将位于Scripts目录中。

You can use environment’s easy_install to install PyCUDA.

dev-env-path/bin/easy_install pycuda

it will give you the same version 0.94rc.

On Windows easy_install.exe will be in Scripts directory.


回答 5

如果是.msi,则可以使用来指定命令行选项msiexec。Python 安装程序本身允许TARGETDIR,但是我不确定distutils是否将此安装到发行版安装程序中。

如果您使用.exe,我认为没有一种干净的方法。一种选择是使用诸如7Zip(或winzip等)之类的程序直接提取exe的内容,然后将relevent文件夹复制到您的虚拟site-packages文件夹中。例如,如果我解压缩“ processing-0.5.2.win32-py2.5.exe”,则会找到一个文件夹“ PLATLIB \ processing”,将其复制到virtualenv路径并可以使用,而不会出现任何运行时问题。(我不确定这是否总是那么简单。)

If it’s a .msi, you might be able to specify command line options using msiexec. The Python installer itself allows TARGETDIR, but I’m not sure if distutils bakes this into distribution installers.

If you’re using a .exe, I don’t think there’s a clean way. One option is to use a program like 7Zip (or winzip, etc) to directly extract the contents of the exe, then copy the relevent folders into your virtual site-packages folder. For example, if I extract “processing-0.5.2.win32-py2.5.exe”, I find a folder “PLATLIB\processing” which I copy to a virtualenv path and use without any runtime problems. (I’m not sure it’s always that simple though.)


在Windows和Mac OS中都使用Python中的默认OS应用程序打开文档

问题:在Windows和Mac OS中都使用Python中的默认OS应用程序打开文档

我需要能够使用Windows和Mac OS中的默认应用程序打开文档。基本上,我想做的事情与您在资源管理器或Finder中双击文档图标时发生的事情相同。用Python做到这一点的最佳方法是什么?

I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?


回答 0

openstart分别是Mac OS / X和Windows的命令解释器。

要从Python调用它们,可以使用subprocessmodule或os.system()

以下是有关使用哪个软件包的注意事项:

  1. 您可以通过调用给他们os.system,该电话有效,但是…

    转义: os.system仅适用于路径名中没有空格或其他shell元字符的文件名(例如A:\abc\def\a.txt),否则需要转义。有shlex.quote针对Unix的系统,但没有Windows的真正标准。也许还会看到python,windows:用shlex解析命令行

    • MacOS / X: os.system("open " + shlex.quote(filename))
    • Windows:也应避免os.system("start " + filename)在适当的地方说话filename
  2. 您也可以通过subprocess模块调用它们,但是…

    对于Python 2.7及更高版本,只需使用

    subprocess.check_call(['open', filename])

    在Python 3.5+中,您可以等效地使用稍微更复杂但也更通用的功能

    subprocess.run(['open', filename], check=True)

    如果您需要一直兼容Python 2.4,则可以使用subprocess.call()并实现自己的错误检查:

    try:
        retcode = subprocess.call("open " + filename, shell=True)
        if retcode < 0:
            print >>sys.stderr, "Child was terminated by signal", -retcode
        else:
            print >>sys.stderr, "Child returned", retcode
    except OSError, e:
        print >>sys.stderr, "Execution failed:", e

    现在,使用的好处是subprocess什么?

    • 安全性:从理论上讲,这是更安全的方法,但是实际上我们需要以一种或另一种方式执行命令行。在这两种环境中,我们都需要环境和服务来解释,获取路径等。在这两种情况下,我们都不执行任意文本,因此它没有固有的“但您可以键入'filename ; rm -rf /'”问题,并且如果文件名可以被破坏,则使用subprocess.call不会给我们带来更多的保护。
    • 错误处理:实际上并没有给我们提供更多的错误检测功能,retcode无论哪种情况我们都取决于 但是在错误的情况下显式引发异常的行为当然可以帮助您注意到是否存在故障(尽管在某些情况下,回溯可能根本不比简单地忽略错误更有用)。
    • 产生一个(非阻塞的)子流程:我们不需要等待子流程,因为我们通过问题陈述来启动一个单独的流程。

    反对“但subprocess首选”。但是,os.system()不建议弃用它,从某种意义上说,它是完成此特定工作的最简单工具。结论:os.system()因此使用也是正确的答案。

    明显的缺点是Windows start命令要求您传递shell=True,否定了使用的大多数好处subprocess

open and start are command-interpreter things for Mac OS/X and Windows respectively, to do this.

To call them from Python, you can either use subprocess module or os.system().

Here are considerations on which package to use:

  1. You can call them via os.system, which works, but…

    Escaping: os.system only works with filenames that don’t have any spaces or other shell metacharacters in the pathname (e.g. A:\abc\def\a.txt), or else these need to be escaped. There is shlex.quote for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex

    • MacOS/X: os.system("open " + shlex.quote(filename))
    • Windows: os.system("start " + filename) where properly speaking filename should be escaped, too.
  2. You can also call them via subprocess module, but…

    For Python 2.7 and newer, simply use

    subprocess.check_call(['open', filename])
    

    In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile

    subprocess.run(['open', filename], check=True)
    

    If you need to be compatible all the way back to Python 2.4, you can use subprocess.call() and implement your own error checking:

    try:
        retcode = subprocess.call("open " + filename, shell=True)
        if retcode < 0:
            print >>sys.stderr, "Child was terminated by signal", -retcode
        else:
            print >>sys.stderr, "Child returned", retcode
    except OSError, e:
        print >>sys.stderr, "Execution failed:", e
    

    Now, what are the advantages of using subprocess?

    • Security: In theory, this is more secure, but in fact we’re needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn’t have an inherent “but you can type 'filename ; rm -rf /'” problem, and if the file name can be corrupted, using subprocess.call gives us little additional protection.
    • Error handling: It doesn’t actually give us any more error detection, we’re still depending on the retcode in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).
    • Spawns a (non-blocking) subprocess: We don’t need to wait for the child process, since we’re by problem statement starting a separate process.

    To the objection “But subprocess is preferred.” However, os.system() is not deprecated, and it’s in some sense the simplest tool for this particular job. Conclusion: using os.system() is therefore also a correct answer.

    A marked disadvantage is that the Windows start command requires you to pass in shell=True which negates most of the benefits of using subprocess.


回答 1

使用subprocessPython 2.4+上可用的模块,而不要使用os.system(),因此您不必处理外壳转义。

import subprocess, os, platform
if platform.system() == 'Darwin':       # macOS
    subprocess.call(('open', filepath))
elif platform.system() == 'Windows':    # Windows
    os.startfile(filepath)
else:                                   # linux variants
    subprocess.call(('xdg-open', filepath))

双括号是因为subprocess.call()希望将序列作为其第一个参数,因此我们在这里使用元组。在具有Gnome的Linux系统上,还有一个gnome-open命令可以执行相同的操作,但是xdg-open它是Free Desktop Foundation标准,并且可以在Linux桌面环境中使用。

Use the subprocess module available on Python 2.4+, not os.system(), so you don’t have to deal with shell escaping.

import subprocess, os, platform
if platform.system() == 'Darwin':       # macOS
    subprocess.call(('open', filepath))
elif platform.system() == 'Windows':    # Windows
    os.startfile(filepath)
else:                                   # linux variants
    subprocess.call(('xdg-open', filepath))

The double parentheses are because subprocess.call() wants a sequence as its first argument, so we’re using a tuple here. On Linux systems with Gnome there is also a gnome-open command that does the same thing, but xdg-open is the Free Desktop Foundation standard and works across Linux desktop environments.


回答 2

我更喜欢:

os.startfile(path, 'open')

请注意,此模块支持在其文件夹和文件中带有空格的文件名,例如

A:\abc\folder with spaces\file with-spaces.txt

python docs)不必添加’open’(这是默认值)。文档特别提到这就像双击Windows资源管理器中的文件图标。

此解决方案仅适用于Windows。

I prefer:

os.startfile(path, 'open')

Note that this module supports filenames that have spaces in their folders and files e.g.

A:\abc\folder with spaces\file with-spaces.txt

(python docs) ‘open’ does not have to be added (it is the default). The docs specifically mention that this is like double-clicking on a file’s icon in Windows Explorer.

This solution is windows only.


回答 3

仅出于完整性考虑(这不是问题),xdg-open将在Linux上执行相同的操作。

Just for completeness (it wasn’t in the question), xdg-open will do the same on Linux.


回答 4

import os
import subprocess

def click_on_file(filename):
    '''Open document with default application in Python.'''
    try:
        os.startfile(filename)
    except AttributeError:
        subprocess.call(['open', filename])
import os
import subprocess

def click_on_file(filename):
    '''Open document with default application in Python.'''
    try:
        os.startfile(filename)
    except AttributeError:
        subprocess.call(['open', filename])

回答 5

如果必须使用启发式方法,则可以考虑webbrowser
它是标准库,尽管有其名称,它也会尝试打开文件:

请注意,在某些平台上,尝试使用此功能打开文件名可能有效并启动操作系统的关联程序。但是,这既不支持也不是可移植的。(参考

我尝试了这段代码,它在Windows 7和Ubuntu Natty中运行良好:

import webbrowser
webbrowser.open("path_to_file")

使用Internet Explorer 8,此代码在Windows XP Professional中也可以正常工作。

If you have to use an heuristic method, you may consider webbrowser.
It’s standard library and despite of its name it would also try to open files:

Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable. (Reference)

I tried this code and it worked fine in Windows 7 and Ubuntu Natty:

import webbrowser
webbrowser.open("path_to_file")

This code also works fine in Windows XP Professional, using Internet Explorer 8.


回答 6

如果subprocess.call()要这样做,在Windows上应如下所示:

import subprocess
subprocess.call(('cmd', '/C', 'start', '', FILE_NAME))

您不能只使用:

subprocess.call(('start', FILE_NAME))

因为start 它不是可执行文件,而是cmd.exe程序的命令。这有效:

subprocess.call(('cmd', '/C', 'start', FILE_NAME))

但前提是FILE_NAME中没有空格。

尽管subprocess.call方法en正确引用了参数,但该start命令具有一种相当奇怪的语法,其中:

start notes.txt

除了:

start "notes.txt"

第一个带引号的字符串应设置窗口的标题。要使其与空格配合使用,我们必须执行以下操作:

start "" "my notes.txt"

这是最上面的代码的作用。

If you want to go the subprocess.call() way, it should look like this on Windows:

import subprocess
subprocess.call(('cmd', '/C', 'start', '', FILE_NAME))

You can’t just use:

subprocess.call(('start', FILE_NAME))

because start is not an executable but a command of the cmd.exe program. This works:

subprocess.call(('cmd', '/C', 'start', FILE_NAME))

but only if there are no spaces in the FILE_NAME.

While subprocess.call method enquotes the parameters properly, the start command has a rather strange syntax, where:

start notes.txt

does something else than:

start "notes.txt"

The first quoted string should set the title of the window. To make it work with spaces, we have to do:

start "" "my notes.txt"

which is what the code on top does.


回答 7

开始不支持长路径名和空格。您必须将其转换为8.3兼容路径。

import subprocess
import win32api

filename = "C:\\Documents and Settings\\user\\Desktop\file.avi"
filename_short = win32api.GetShortPathName(filename)

subprocess.Popen('start ' + filename_short, shell=True )

该文件必须存在才能与API调用一起使用。

Start does not support long path names and white spaces. You have to convert it to 8.3 compatible paths.

import subprocess
import win32api

filename = "C:\\Documents and Settings\\user\\Desktop\file.avi"
filename_short = win32api.GetShortPathName(filename)

subprocess.Popen('start ' + filename_short, shell=True )

The file has to exist in order to work with the API call.


回答 8

我已经很晚了,但是这里是使用Windows API的解决方案。这总是打开关联的应用程序。

import ctypes

shell32 = ctypes.windll.shell32
file = 'somedocument.doc'

shell32.ShellExecuteA(0,"open",file,0,0,5)

很多魔术常数。第一个零是当前程序的hwnd。可以为零。另外两个零是可选参数(参数和目录)。5 == SW_SHOW,它指定如何执行应用程序。阅读 ShellExecute API文档以获取更多信息。

I am pretty late to the lot, but here is a solution using the windows api. This always opens the associated application.

import ctypes

shell32 = ctypes.windll.shell32
file = 'somedocument.doc'

shell32.ShellExecuteA(0,"open",file,0,0,5)

A lot of magic constants. The first zero is the hwnd of the current program. Can be zero. The other two zeros are optional parameters (parameters and directory). 5 == SW_SHOW, it specifies how to execute the app. Read the ShellExecute API docs for more info.


回答 9

在Mac OS上,您可以调用“打开”

import os
os.popen("open myfile.txt")

这将使用TextEdit打开该文件,或者将此文件类型设置为默认应用程序

on mac os you can call ‘open’

import os
os.popen("open myfile.txt")

this would open the file with TextEdit, or whatever app is set as default for this filetype


回答 10

如果要指定用于在Mac OS X上打开文件的应用程序,请使用以下命令: os.system("open -a [app name] [file name]")

If you want to specify the app to open the file with on Mac OS X, use this: os.system("open -a [app name] [file name]")


回答 11

在Windows 8.1上,下面的方法已经起作用,而其他给定的方法却subprocess.call失败了,并且路径中有空格。

subprocess.call('cmd /c start "" "any file path with spaces"')

通过之前利用此答案和其他答案,这是一个内联代码,可在多个平台上工作。

import sys, os, subprocess
subprocess.call(('cmd /c start "" "'+ filepath +'"') if os.name is 'nt' else ('open' if sys.platform.startswith('darwin') else 'xdg-open', filepath))

On windows 8.1, below have worked while other given ways with subprocess.call fails with path has spaces in it.

subprocess.call('cmd /c start "" "any file path with spaces"')

By utilizing this and other’s answers before, here’s an inline code which works on multiple platforms.

import sys, os, subprocess
subprocess.call(('cmd /c start "" "'+ filepath +'"') if os.name is 'nt' else ('open' if sys.platform.startswith('darwin') else 'xdg-open', filepath))

回答 12

os.startfile(path, 'open')在Windows下,这是一个好习惯,因为当目录中存在空格时,os.system('start', path_name)无法正确打开应用程序;当目录中存在i18n时,则os.system需要将unicode更改为Windows中控制台的编解码器。

os.startfile(path, 'open') under Windows is good because when spaces exist in the directory, os.system('start', path_name) can’t open the app correctly and when the i18n exist in the directory, os.system needs to change the unicode to the codec of the console in Windows.


Windows上的RuntimeError尝试Python多处理

问题:Windows上的RuntimeError尝试Python多处理

我正在尝试在Windows机器上使用Threading and Multiprocessing的第一个正式python程序。我无法启动进程,但是python给出了以下消息。问题是,我没有在模块中启动线程。线程在类内的单独模块中处理。

编辑:顺便说一句,此代码在ubuntu上运行良好。在窗户上不太

RuntimeError: 
            Attempt to start a new process before the current process
            has finished its bootstrapping phase.
            This probably means that you are on Windows and you have
            forgotten to use the proper idiom in the main module:
                if __name__ == '__main__':
                    freeze_support()
                    ...
            The "freeze_support()" line can be omitted if the program
            is not going to be frozen to produce a Windows executable.

我的原始代码很长,但是我能够以节略的版本重现该错误。它分为两个文件,第一个是主模块,除了导入处理进程/线程和调用方法的模块外,几乎没有其他作用。第二个模块是代码的关键所在。


testMain.py:

import parallelTestModule

extractor = parallelTestModule.ParallelExtractor()
extractor.runInParallel(numProcesses=2, numThreads=4)

parallelTestModule.py:

import multiprocessing
from multiprocessing import Process
import threading

class ThreadRunner(threading.Thread):
    """ This class represents a single instance of a running thread"""
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        print self.name,'\n'

class ProcessRunner:
    """ This class represents a single instance of a running process """
    def runp(self, pid, numThreads):
        mythreads = []
        for tid in range(numThreads):
            name = "Proc-"+str(pid)+"-Thread-"+str(tid)
            th = ThreadRunner(name)
            mythreads.append(th) 
        for i in mythreads:
            i.start()
        for i in mythreads:
            i.join()

class ParallelExtractor:    
    def runInParallel(self, numProcesses, numThreads):
        myprocs = []
        prunner = ProcessRunner()
        for pid in range(numProcesses):
            pr = Process(target=prunner.runp, args=(pid, numThreads)) 
            myprocs.append(pr) 
#        if __name__ == 'parallelTestModule':    #This didnt work
#        if __name__ == '__main__':              #This obviously doesnt work
#        multiprocessing.freeze_support()        #added after seeing error to no avail
        for i in myprocs:
            i.start()

        for i in myprocs:
            i.join()

I am trying my very first formal python program using Threading and Multiprocessing on a windows machine. I am unable to launch the processes though, with python giving the following message. The thing is, I am not launching my threads in the main module. The threads are handled in a separate module inside a class.

EDIT: By the way this code runs fine on ubuntu. Not quite on windows

RuntimeError: 
            Attempt to start a new process before the current process
            has finished its bootstrapping phase.
            This probably means that you are on Windows and you have
            forgotten to use the proper idiom in the main module:
                if __name__ == '__main__':
                    freeze_support()
                    ...
            The "freeze_support()" line can be omitted if the program
            is not going to be frozen to produce a Windows executable.

My original code is pretty long, but I was able to reproduce the error in an abridged version of the code. It is split in two files, the first is the main module and does very little other than import the module which handles processes/threads and calls a method. The second module is where the meat of the code is.


testMain.py:

import parallelTestModule

extractor = parallelTestModule.ParallelExtractor()
extractor.runInParallel(numProcesses=2, numThreads=4)

parallelTestModule.py:

import multiprocessing
from multiprocessing import Process
import threading

class ThreadRunner(threading.Thread):
    """ This class represents a single instance of a running thread"""
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        print self.name,'\n'

class ProcessRunner:
    """ This class represents a single instance of a running process """
    def runp(self, pid, numThreads):
        mythreads = []
        for tid in range(numThreads):
            name = "Proc-"+str(pid)+"-Thread-"+str(tid)
            th = ThreadRunner(name)
            mythreads.append(th) 
        for i in mythreads:
            i.start()
        for i in mythreads:
            i.join()

class ParallelExtractor:    
    def runInParallel(self, numProcesses, numThreads):
        myprocs = []
        prunner = ProcessRunner()
        for pid in range(numProcesses):
            pr = Process(target=prunner.runp, args=(pid, numThreads)) 
            myprocs.append(pr) 
#        if __name__ == 'parallelTestModule':    #This didnt work
#        if __name__ == '__main__':              #This obviously doesnt work
#        multiprocessing.freeze_support()        #added after seeing error to no avail
        for i in myprocs:
            i.start()

        for i in myprocs:
            i.join()

回答 0

在Windows上,子进程将在启动时导入(即执行)主模块。您需要if __name__ == '__main__':在主模块中插入防护,以避免递归创建子流程。

已修改testMain.py

import parallelTestModule

if __name__ == '__main__':    
    extractor = parallelTestModule.ParallelExtractor()
    extractor.runInParallel(numProcesses=2, numThreads=4)

On Windows the subprocesses will import (i.e. execute) the main module at start. You need to insert an if __name__ == '__main__': guard in the main module to avoid creating subprocesses recursively.

Modified testMain.py:

import parallelTestModule

if __name__ == '__main__':    
    extractor = parallelTestModule.ParallelExtractor()
    extractor.runInParallel(numProcesses=2, numThreads=4)

回答 1

尝试将代码放入testMain.py的主函数中

import parallelTestModule

if __name__ ==  '__main__':
  extractor = parallelTestModule.ParallelExtractor()
  extractor.runInParallel(numProcesses=2, numThreads=4)

文档

"For an explanation of why (on Windows) the if __name__ == '__main__' 
part is necessary, see Programming guidelines."

哪说

“确保主模块可以由新的Python解释器安全地导入,而不会引起意外的副作用(例如,启动新进程)。”

… 通过使用 if __name__ == '__main__'

Try putting your code inside a main function in testMain.py

import parallelTestModule

if __name__ ==  '__main__':
  extractor = parallelTestModule.ParallelExtractor()
  extractor.runInParallel(numProcesses=2, numThreads=4)

See the docs:

"For an explanation of why (on Windows) the if __name__ == '__main__' 
part is necessary, see Programming guidelines."

which say

“Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).”

… by using if __name__ == '__main__'


回答 2

尽管较早的答案是正确的,但有一点复杂之处将有助于进一步说明。

如果您的主模块导入了另一个模块,在该模块中定义了全局变量或类成员变量并将其初始化为(或使用)一些新对象,则可能必须以相同的方式来限制导入:

if __name__ ==  '__main__':
  import my_module

Though the earlier answers are correct, there’s a small complication it would help to remark on.

In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:

if __name__ ==  '__main__':
  import my_module

回答 3

正如@Ofer所说,当您使用其他库或模块时,应将所有库或模块导入其中。 if __name__ == '__main__':

因此,就我而言,这样结束:

if __name__ == '__main__':       
    import librosa
    import os
    import pandas as pd
    run_my_program()

As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':

So, in my case, ended like this:

if __name__ == '__main__':       
    import librosa
    import os
    import pandas as pd
    run_my_program()

回答 4

就我而言,这是代码中的一个简单错误,在创建变量之前就使用了变量。在尝试上述解决方案之前,值得检查一下。上帝知道为什么我得到这个特殊的错误信息。

In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.


获取MAC地址

问题:获取MAC地址

我需要一种跨平台的方法来在运行时确定计算机的MAC地址。对于Windows,可以使用“ wmi”模块,在Linux下,我能找到的唯一方法是运行ifconfig并在其输出中运行正则表达式。我不喜欢使用只能在一个OS上运行的程序包,而且更不用说容易出错的语法解析另一个程序的输出了。

有谁知道跨平台方法(Windows和Linux)方法来获取MAC地址?如果没有,还有谁比我上面列出的方法更优雅?

I need a cross platform method of determining the MAC address of a computer at run time. For windows the ‘wmi’ module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don’t like using a package that only works on one OS, and parsing the output of another program doesn’t seem very elegant not to mention error prone.

Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?


回答 0

Python 2.5包含一个uuid实现(至少在一个版本中),该实现需要mac地址。您可以轻松地将mac查找功能导入您自己的代码中:

from uuid import getnode as get_mac
mac = get_mac()

返回值是作为48位整数的mac地址。

Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:

from uuid import getnode as get_mac
mac = get_mac()

The return value is the mac address as 48 bit integer.


回答 1

在Linux下针对此问题的纯python解决方案,用于获取特定本地接口的MAC,最初由vishnubob作为注释发布,并在本activestate食谱中由Ben Mackey进行了改进

#!/usr/bin/python

import fcntl, socket, struct

def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ':'.join(['%02x' % ord(char) for char in info[18:24]])

print getHwAddr('eth0')

这是Python 3兼容的代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import fcntl
import socket
import struct


def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
    return ':'.join('%02x' % b for b in info[18:24])


def main():
    print(getHwAddr('enp0s8'))


if __name__ == "__main__":
    main()

The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in this activestate recipe

#!/usr/bin/python

import fcntl, socket, struct

def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ':'.join(['%02x' % ord(char) for char in info[18:24]])

print getHwAddr('eth0')

This is the Python 3 compatible code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import fcntl
import socket
import struct


def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
    return ':'.join('%02x' % b for b in info[18:24])


def main():
    print(getHwAddr('enp0s8'))


if __name__ == "__main__":
    main()

回答 2

netifaces是一个很好的模块,可用于获取mac地址(和其他地址)。它是跨平台的,比使用套接字或uuid更有意义。

>>> import netifaces
>>> netifaces.interfaces()
['lo', 'eth0', 'tun2']

>>> netifaces.ifaddresses('eth0')[netifaces.AF_LINK]
[{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]

netifaces is a good module to use for getting the mac address (and other addresses). It’s crossplatform and makes a bit more sense than using socket or uuid.

>>> import netifaces
>>> netifaces.interfaces()
['lo', 'eth0', 'tun2']

>>> netifaces.ifaddresses('eth0')[netifaces.AF_LINK]
[{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]


回答 3

您应该注意的另一件事是,uuid.getnode()可以通过返回随机的48位数字来伪造MAC地址,这可能不是您所期望的。另外,也没有明显的迹象表明MAC地址已被伪造,但是您可以通过调用getnode()两次并查看结果是否变化来检测到它。如果两个调用都返回了相同的值,则说明您具有MAC地址,否则得到的是伪造的地址。

>>> print uuid.getnode.__doc__
Get the hardware address as a 48-bit positive integer.

    The first time this runs, it may launch a separate program, which could
    be quite slow.  If all attempts to obtain the hardware address fail, we
    choose a random 48-bit number with its eighth bit set to 1 as recommended
    in RFC 4122.

One other thing that you should note is that uuid.getnode() can fake the MAC addr by returning a random 48-bit number which may not be what you are expecting. Also, there’s no explicit indication that the MAC address has been faked, but you could detect it by calling getnode() twice and seeing if the result varies. If the same value is returned by both calls, you have the MAC address, otherwise you are getting a faked address.

>>> print uuid.getnode.__doc__
Get the hardware address as a 48-bit positive integer.

    The first time this runs, it may launch a separate program, which could
    be quite slow.  If all attempts to obtain the hardware address fail, we
    choose a random 48-bit number with its eighth bit set to 1 as recommended
    in RFC 4122.

回答 4

有时我们有多个网络接口。

找出特定接口的mac地址的一种简单方法是:

def getmac(interface):

  try:
    mac = open('/sys/class/net/'+interface+'/address').readline()
  except:
    mac = "00:00:00:00:00:00"

  return mac[0:17]

调用方法很简单

myMAC = getmac("wlan0")

Sometimes we have more than one net interface.

A simple method to find out the mac address of a specific interface, is:

def getmac(interface):

  try:
    mac = open('/sys/class/net/'+interface+'/address').readline()
  except:
    mac = "00:00:00:00:00:00"

  return mac[0:17]

to call the method is simple

myMAC = getmac("wlan0")

回答 5

从这里使用我的答案:https : //stackoverflow.com/a/18031868/2362361

重要的是要知道您想要MAC到哪个iface,因为可能存在很多(蓝牙,几个nic等)。

当您知道需要使用MAC的iface的IP netifaces(使用PyPI中提供)时,就可以完成此工作:

import netifaces as nif
def mac_for_ip(ip):
    'Returns a list of MACs for interfaces that have given IP, returns None if not found'
    for i in nif.interfaces():
        addrs = nif.ifaddresses(i)
        try:
            if_mac = addrs[nif.AF_LINK][0]['addr']
            if_ip = addrs[nif.AF_INET][0]['addr']
        except IndexError, KeyError: #ignore ifaces that dont have MAC or IP
            if_mac = if_ip = None
        if if_ip == ip:
            return if_mac
    return None

测试:

>>> mac_for_ip('169.254.90.191')
'2c:41:38:0a:94:8b'

Using my answer from here: https://stackoverflow.com/a/18031868/2362361

It would be important to know to which iface you want the MAC for since many can exist (bluetooth, several nics, etc.).

This does the job when you know the IP of the iface you need the MAC for, using netifaces (available in PyPI):

import netifaces as nif
def mac_for_ip(ip):
    'Returns a list of MACs for interfaces that have given IP, returns None if not found'
    for i in nif.interfaces():
        addrs = nif.ifaddresses(i)
        try:
            if_mac = addrs[nif.AF_LINK][0]['addr']
            if_ip = addrs[nif.AF_INET][0]['addr']
        except IndexError, KeyError: #ignore ifaces that dont have MAC or IP
            if_mac = if_ip = None
        if if_ip == ip:
            return if_mac
    return None

Testing:

>>> mac_for_ip('169.254.90.191')
'2c:41:38:0a:94:8b'

回答 6

您可以使用跨平台的psutil进行此操作:

import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]

You can do this with psutil which is cross-platform:

import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]

回答 7

请注意,您可以使用条件导入在python中构建自己的跨平台库。例如

import platform
if platform.system() == 'Linux':
  import LinuxMac
  mac_address = LinuxMac.get_mac_address()
elif platform.system() == 'Windows':
  # etc

这将允许您使用os.system调用或特定于平台的库。

Note that you can build your own cross-platform library in python using conditional imports. e.g.

import platform
if platform.system() == 'Linux':
  import LinuxMac
  mac_address = LinuxMac.get_mac_address()
elif platform.system() == 'Windows':
  # etc

This will allow you to use os.system calls or platform-specific libraries.


回答 8

如果您不介意依赖,则跨平台的getmac软件包将对此有效。它适用于Python 2.7+和3.4+。它将尝试许多不同的方法,直到获得地址或返回None。

from getmac import get_mac_address
eth_mac = get_mac_address(interface="eth0")
win_mac = get_mac_address(interface="Ethernet 3")
ip_mac = get_mac_address(ip="192.168.0.1")
ip6_mac = get_mac_address(ip6="::1")
host_mac = get_mac_address(hostname="localhost")
updated_mac = get_mac_address(ip="10.0.0.1", network_request=True)

免责声明:我是软件包的作者。

更新(2019年1月14日):该软件包现在仅支持Python 2.7+和3.4+。如果您需要使用旧版本的Python(2.5、2.6、3.2、3.3),则仍可以使用该软件包的旧版本。

The cross-platform getmac package will work for this, if you don’t mind taking on a dependency. It works with Python 2.7+ and 3.4+. It will try many different methods until either getting a address or returning None.

from getmac import get_mac_address
eth_mac = get_mac_address(interface="eth0")
win_mac = get_mac_address(interface="Ethernet 3")
ip_mac = get_mac_address(ip="192.168.0.1")
ip6_mac = get_mac_address(ip6="::1")
host_mac = get_mac_address(hostname="localhost")
updated_mac = get_mac_address(ip="10.0.0.1", network_request=True)

Disclaimer: I am the author of the package.

Update (Jan 14 2019): the package now only supports Python 2.7+ and 3.4+. You can still use an older version of the package if you need to work with an older Python (2.5, 2.6, 3.2, 3.3).


回答 9

要获取eth0接口MAC地址,

import psutil

nics = psutil.net_if_addrs()['eth0']

for interface in nics:
   if interface.family == 17:
      print(interface.address)

To get the eth0 interface MAC address,

import psutil

nics = psutil.net_if_addrs()['eth0']

for interface in nics:
   if interface.family == 17:
      print(interface.address)

回答 10

我不知道统一的方式,但是以下内容可能对您有用:

http://www.codeguru.com/Cpp/IN/network/networkinformation/article.php/c5451

在这种情况下,我要做的就是将它们包装成一个函数,并根据操作系统运行适当的命令,根据需要进行解析,并仅返回所需格式的MAC地址。当然,除了您只需要执行一次,并且与主代码相比,它看起来更干净以外,其他所有内容都一样。

I dont know of a unified way, but heres something that you might find useful:

http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451

What I would do in this case would be to wrap these up into a function, and based on the OS it would run the proper command, parse as required and return only the MAC address formatted as you want. Its ofcourse all the same, except that you only have to do it once, and it looks cleaner from the main code.


回答 11

对于Linux,让我介绍一个shell脚本,该脚本将显示mac地址并允许对其进行更改(MAC嗅探)。

 ifconfig eth0 | grep HWaddr |cut -dH -f2|cut -d\  -f2
 00:26:6c:df:c3:95

减少参数(我不是专家)可以尝试:

ifconfig etho | grep HWaddr
eth0      Link encap:Ethernet  HWaddr 00:26:6c:df:c3:95  

要更改MAC,我们可以这样做:

ifconfig eth0 down
ifconfig eth0 hw ether 00:80:48:BA:d1:30
ifconfig eth0 up

会将mac地址更改为00:80:48:BA:d1:30(临时,重新启动后将还原为实际地址)。

For Linux let me introduce a shell script that will show the mac address and allows to change it (MAC sniffing).

 ifconfig eth0 | grep HWaddr |cut -dH -f2|cut -d\  -f2
 00:26:6c:df:c3:95

Cut arguements may dffer (I am not an expert) try:

ifconfig etho | grep HWaddr
eth0      Link encap:Ethernet  HWaddr 00:26:6c:df:c3:95  

To change MAC we may do:

ifconfig eth0 down
ifconfig eth0 hw ether 00:80:48:BA:d1:30
ifconfig eth0 up

will change mac address to 00:80:48:BA:d1:30 (temporarily, will restore to actual one upon reboot).


回答 12

或者,

import uuid
mac_id=(':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff)

Alternatively,

import uuid
mac_id=(':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff)

回答 13

For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.

struct ifreq    ifr;
uint8_t         macaddr[6];

if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
    return -1;

strcpy(ifr.ifr_name, "eth0");

if (ioctl(s, SIOCGIFHWADDR, (void *)&ifr) == 0) {
    if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
        memcpy(macaddr, ifr.ifr_hwaddr.sa_data, 6);
        return 0;
... etc ...

You’ve tagged the question “python”. I don’t know of an existing Python module to get this information. You could use ctypes to call the ioctl directly.

For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.

struct ifreq    ifr;
uint8_t         macaddr[6];

if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
    return -1;

strcpy(ifr.ifr_name, "eth0");

if (ioctl(s, SIOCGIFHWADDR, (void *)&ifr) == 0) {
    if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
        memcpy(macaddr, ifr.ifr_hwaddr.sa_data, 6);
        return 0;
... etc ...

You’ve tagged the question “python”. I don’t know of an existing Python module to get this information. You could use ctypes to call the ioctl directly.


Windows上的Python os.path.join

问题:Windows上的Python os.path.join

我正在尝试学习python,正在制作一个将输出脚本的程序。我想使用os.path.join,但是很困惑。根据文档,如果我说:

os.path.join('c:', 'sourcedir')

我懂了"C:sourcedir"。根据文档,这是正常的,对吗?

但是当我使用copytree命令时,Python将以所需的方式输出它,例如:

import shutil
src = os.path.join('c:', 'src')
dst = os.path.join('c:', 'dst')
shutil.copytree(src, dst)

这是我得到的错误代码:

WindowsError:[错误3]系统找不到指定的路径:'C:src /*.*'

如果我用换行os.path.joinos.path.normpath则会得到相同的错误。

如果os.path.join不能以这种方式使用它,那么我对其目的感到困惑。

根据Stack Overflow建议的页面,在连接中不应该使用斜杠-是的,我认为是正确的吗?

I am trying to learn python and am making a program that will output a script. I want to use os.path.join, but am pretty confused. According to the docs if I say:

os.path.join('c:', 'sourcedir')

I get "C:sourcedir". According to the docs, this is normal, right?

But when I use the copytree command, Python will output it the desired way, for example:

import shutil
src = os.path.join('c:', 'src')
dst = os.path.join('c:', 'dst')
shutil.copytree(src, dst)

Here is the error code I get:

WindowsError: [Error 3] The system cannot find the path specified: 'C:src/*.*'

If I wrap the os.path.join with os.path.normpath I get the same error.

If this os.path.join can’t be used this way, then I am confused as to its purpose.

According to the pages suggested by Stack Overflow, slashes should not be used in join—that is correct, I assume?


回答 0

Windows具有每个驱动器的当前目录的概念。因此,"c:sourcedir"意味着在当前C:目录中有“ sourcedir”,并且您需要指定一个绝对目录。

这些中的任何一个都应该工作并给出相同的结果,但是目前我还没有启动Windows VM进行仔细检查:

"c:/sourcedir"
os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")

Windows has a concept of current directory for each drive. Because of that, "c:sourcedir" means “sourcedir” inside the current C: directory, and you’ll need to specify an absolute directory.

Any of these should work and give the same result, but I don’t have a Windows VM fired up at the moment to double check:

"c:/sourcedir"
os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")

回答 1

要进一步讲究知识,最符合python doc的答案是:

mypath = os.path.join('c:', os.sep, 'sourcedir')

由于您还需要os.sep作为posix根路径:

mypath = os.path.join(os.sep, 'usr', 'lib')

To be even more pedantic, the most python doc consistent answer would be:

mypath = os.path.join('c:', os.sep, 'sourcedir')

Since you also need os.sep for the posix root path:

mypath = os.path.join(os.sep, 'usr', 'lib')

回答 2

之所以os.path.join('C:', 'src')无法正常工作,是因为您链接到了文档中的某些内容:

请注意,在Windows上,由于每个驱动器都有一个当前目录,所以os.path.join(“ c:”,“ foo”)表示相对于驱动器C:(c:foo)上当前目录的路径,而不是c :\ foo

正如ghostdog所说,您可能想要 mypath=os.path.join('c:\\', 'sourcedir')

The reason os.path.join('C:', 'src') is not working as you expect is because of something in the documentation that you linked to:

Note that on Windows, since there is a current directory for each drive, os.path.join(“c:”, “foo”) represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

As ghostdog said, you probably want mypath=os.path.join('c:\\', 'sourcedir')


回答 3

对于在Windows和Linux上均可使用的与系统无关的解决方案,无论输入路径如何,都可以使用 os.path.join(os.sep, rootdir + os.sep, targetdir)

在窗口上:

>>> os.path.join(os.sep, "C:" + os.sep, "Windows")
'C:\\Windows'

在Linux上:

>>> os.path.join(os.sep, "usr" + os.sep, "lib")
'/usr/lib'

For a system-agnostic solution that works on both Windows and Linux, no matter what the input path, one could use os.path.join(os.sep, rootdir + os.sep, targetdir)

On WIndows:

>>> os.path.join(os.sep, "C:" + os.sep, "Windows")
'C:\\Windows'

On Linux:

>>> os.path.join(os.sep, "usr" + os.sep, "lib")
'/usr/lib'

回答 4

要学究,将/或\硬编码为路径分隔符可能不好。也许这是最好的?

mypath = os.path.join('c:%s' % os.sep, 'sourcedir')

要么

mypath = os.path.join('c:' + os.sep, 'sourcedir')

To be pedantic, it’s probably not good to hardcode either / or \ as the path separator. Maybe this would be best?

mypath = os.path.join('c:%s' % os.sep, 'sourcedir')

or

mypath = os.path.join('c:' + os.sep, 'sourcedir')

回答 5

我会说这是一个(windows)python错误。

为什么要臭虫?

我认为这句话应该是 True

os.path.join(*os.path.dirname(os.path.abspath(__file__)).split(os.path.sep))==os.path.dirname(os.path.abspath(__file__))

但这是False在Windows机器上。

I’d say this is a (windows)python bug.

Why bug?

I think this statement should be True

os.path.join(*os.path.dirname(os.path.abspath(__file__)).split(os.path.sep))==os.path.dirname(os.path.abspath(__file__))

But it is False on windows machines.


回答 6

加入Windows路径,请尝试

mypath=os.path.join('c:\\', 'sourcedir')

基本上,您将需要逃脱斜线

to join a windows path, try

mypath=os.path.join('c:\\', 'sourcedir')

basically, you will need to escape the slash


回答 7

您可以使用几种可能的方法来处理Windows上的路径,从最硬编码的方法(如使用原始字符串文字或转义反斜杠)到最少的方法。以下是一些可以按预期工作的示例。使用更适合您需求的产品。

In[1]: from os.path import join, isdir

In[2]: from os import sep

In[3]: isdir(join("c:", "\\", "Users"))
Out[3]: True

In[4]: isdir(join("c:", "/", "Users"))
Out[4]: True

In[5]: isdir(join("c:", sep, "Users"))
Out[5]: True

You have a few possible approaches to treat path on Windows, from the most hardcoded ones (as using raw string literals or escaping backslashes) to the least ones. Here follows a few examples that will work as expected. Use what better fits your needs.

In[1]: from os.path import join, isdir

In[2]: from os import sep

In[3]: isdir(join("c:", "\\", "Users"))
Out[3]: True

In[4]: isdir(join("c:", "/", "Users"))
Out[4]: True

In[5]: isdir(join("c:", sep, "Users"))
Out[5]: True

回答 8

同意@ georg-

我会说为什么我们需要la脚os.path.join-更好地使用str.joinunicode.join例如

sys.path.append('{0}'.join(os.path.dirname(__file__).split(os.path.sep)[0:-1]).format(os.path.sep))

Consent with @georg-

I would say then why we need lame os.path.join– better to use str.join or unicode.join e.g.

sys.path.append('{0}'.join(os.path.dirname(__file__).split(os.path.sep)[0:-1]).format(os.path.sep))

回答 9

回答您的评论:“其他’//”c:’,’c:\\’不起作用(C:\\创建了两个反斜杠,C:\根本不起作用)”

在Windows上,using os.path.join('c:', 'sourcedir') 将自动\\sourcedir前面添加两个反斜杠。

解析路径,因为python在Windows上也可以使用正斜杠-> “/”,只需.replace('\\','/')os.path.join如下: –

os.path.join('c:\\', 'sourcedir').replace('\\','/')

例如: os.path.join('c:\\', 'temp').replace('\\','/')

输出: ‘C:/ temp’

answering to your comment : “the others ‘//’ ‘c:’, ‘c:\\’ did not work (C:\\ created two backslashes, C:\ didn’t work at all)”

On windows using os.path.join('c:', 'sourcedir') will automatically add two backslashes \\ in front of sourcedir.

To resolve the path, as python works on windows also with forward slashes -> ‘/’, simply add .replace('\\','/') with os.path.join as below:-

os.path.join('c:\\', 'sourcedir').replace('\\','/')

e.g: os.path.join('c:\\', 'temp').replace('\\','/')

output : ‘C:/temp’


回答 10

所提出的解决方案很有趣并且可以提供很好的参考,但是它们只是部分令人满意。当您遇到单个特定情况或知道输入字符串的格式时,可以手动添加分隔符,但是在某些情况下,您可能希望对通用输入进行编程编程。

经过一些试验,我相信标准是,如果第一个段是驱动器号(即单个字母后跟一个冒号),则不添加路径定界符,无论它是否对应于实际单位。

例如:

import os
testval = ['c:','c:\\','d:','j:','jr:','data:']

for t in testval:
    print ('test value: ',t,', join to "folder"',os.path.join(t,'folder'))
test value:  c: , join to "folder" c:folder
test value:  c:\ , join to "folder" c:\folder
test value:  d: , join to "folder" d:folder
test value:  j: , join to "folder" j:folder
test value:  jr: , join to "folder" jr:\folder
test value:  data: , join to "folder" data:\folder

测试标准并进行路径校正的一种便捷方法是,os.path.splitdrive将第一个返回的元素与测试值进行比较,例如t+os.path.sep if os.path.splitdrive(t)[0]==t else t

测试:

for t in testval:
    corrected = t+os.path.sep if os.path.splitdrive(t)[0]==t else t
    print ('original: %s\tcorrected: %s'%(t,corrected),' join corrected->',os.path.join(corrected,'folder'))
original: c:    corrected: c:\  join corrected-> c:\folder
original: c:\   corrected: c:\  join corrected-> c:\folder
original: d:    corrected: d:\  join corrected-> d:\folder
original: j:    corrected: j:\  join corrected-> j:\folder
original: jr:   corrected: jr:  join corrected-> jr:\folder
original: data: corrected: data:  join corrected-> data:\folder

可能可以对其进行改进以使其更适合尾随空间,并且我仅在Windows上对其进行了测试,但我希望它能给出一个主意。另请参见Os.path:您可以解释这种行为吗?有关Windows以外的其他系统的有趣信息。

The proposed solutions are interesting and offer a good reference, however they are only partially satisfying. It is ok to manually add the separator when you have a single specific case or you know the format of the input string, but there can be cases where you want to do it programmatically on generic inputs.

With a bit of experimenting, I believe the criteria is that the path delimiter is not added if the first segment is a drive letter, meaning a single letter followed by a colon, no matter if it corresponds to a real unit.

For example:

import os
testval = ['c:','c:\\','d:','j:','jr:','data:']

for t in testval:
    print ('test value: ',t,', join to "folder"',os.path.join(t,'folder'))
test value:  c: , join to "folder" c:folder
test value:  c:\ , join to "folder" c:\folder
test value:  d: , join to "folder" d:folder
test value:  j: , join to "folder" j:folder
test value:  jr: , join to "folder" jr:\folder
test value:  data: , join to "folder" data:\folder

A convenient way to test for the criteria and apply a path correction can be to use os.path.splitdrive comparing the first returned element to the test value, like t+os.path.sep if os.path.splitdrive(t)[0]==t else t.

Test:

for t in testval:
    corrected = t+os.path.sep if os.path.splitdrive(t)[0]==t else t
    print ('original: %s\tcorrected: %s'%(t,corrected),' join corrected->',os.path.join(corrected,'folder'))
original: c:    corrected: c:\  join corrected-> c:\folder
original: c:\   corrected: c:\  join corrected-> c:\folder
original: d:    corrected: d:\  join corrected-> d:\folder
original: j:    corrected: j:\  join corrected-> j:\folder
original: jr:   corrected: jr:  join corrected-> jr:\folder
original: data: corrected: data:  join corrected-> data:\folder

it can be probably be improved to be more robust for trailing spaces, and I have tested it only on windows, but I hope it gives an idea. See also Os.path : can you explain this behavior? for interesting details on systems other then windows.


我的计算机上的Python使用哪个版本的Visual Studio进行编译?

问题:我的计算机上的Python使用哪个版本的Visual Studio进行编译?

我正在尝试找出用于在计算机上编译Python的Visual Studio版本

它说

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32

我不明白的是这个MSC V.1500称呼。这是否意味着它是使用Visual Studio 2005编译的?我在http://python.org上找不到此信息。

I am trying to find out the version of Visual Studio that is used to compile the Python on my computer

It says

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32

What I do not understand is this MSC V.1500 designation. Does it mean it is compiled with Visual Studio 2005? I cannot find this information on http://python.org.


回答 0

Visual C ++版本_MSC_VER            
Visual C ++ 4.x 1000
Visual C ++ 5 1100
Visual C ++ 6 1200
Visual C ++ .NET 1300
Visual C ++ .NET 2003 1310
Visual C ++ 2005(8.0)1400
Visual C ++ 2008(9.0)1500
Visual C ++ 2010(10.0)1600
Visual C ++ 2012(11.0)1700年
Visual C ++ 2013(12.0)1800
Visual C ++ 2015(14.0)1900年

Visual C ++ 2017(15.0)1910年
Visual C ++ 2017(15.3)1911年
Visual C ++ 2017(15.5)1912年
Visual C ++ 2017(15.6)1913年
Visual C ++ 2017(15.7)1914年
Visual C ++ 2017(15.8)1915年
Visual C ++ 2017(15.9)1916年

Visual C ++ 2019 RTW(16.0)1920
Visual C ++ 2019(16.1)1921年
Visual C ++ 2019(16.2)1922年
Visual C ++ 2019(16.3)1923年

来源:_MSC_VER预定义宏的文档

Visual C++ version            _MSC_VER
Visual C++ 4.x                  1000
Visual C++ 5                    1100
Visual C++ 6                    1200
Visual C++ .NET                 1300
Visual C++ .NET 2003            1310
Visual C++ 2005  (8.0)          1400
Visual C++ 2008  (9.0)          1500
Visual C++ 2010 (10.0)          1600
Visual C++ 2012 (11.0)          1700
Visual C++ 2013 (12.0)          1800
Visual C++ 2015 (14.0)          1900

Visual C++ 2017 (15.0)          1910
Visual C++ 2017 (15.3)          1911
Visual C++ 2017 (15.5)          1912
Visual C++ 2017 (15.6)          1913
Visual C++ 2017 (15.7)          1914
Visual C++ 2017 (15.8)          1915
Visual C++ 2017 (15.9)          1916

Visual C++ 2019 RTW (16.0)      1920
Visual C++ 2019 (16.1)          1921
Visual C++ 2019 (16.2)          1922
Visual C++ 2019 (16.3)          1923

Source: the documentation for the _MSC_VER predefined macro


回答 1

MSC v.1500根据OpenCobol论坛(所有地方)上的此主题,看来是Visual C ++ 2008 。

预定义宏上MSDN页面指示1500是_MSC_VER宏的结果。

另一篇论坛帖子中提到

(供参考,Visual Studio 2003具有_MSC_VER= 1310; Visual Studio 2005具有_MSC_VER= 1400; Visual Studio 2008具有_MSC_VER=1500。)

上面的MSDN链接表示1600表示VS2010。

奇怪的是,我无法_MSC_VER在MSDN上找到有关早期值的信息。

MSC v.1500 appears to be Visual C++ 2008 according to this thread on the OpenCobol forums (of all places).

The MSDN page on Predefined Macros indicates 1500 to be the result of the _MSC_VER macro.

This other forum post mentions that

(For reference, Visual Studio 2003 has _MSC_VER = 1310; Visual Studio 2005 has _MSC_VER = 1400; Visual Studio 2008 has _MSC_VER = 1500.)

The above MSDN link said that 1600 indicates VS2010.

Strangely, I wasn’t able to find that info about the earlier _MSC_VER values on MSDN.


Windows上的pip安装访问被拒绝

问题:Windows上的pip安装访问被拒绝

我试图运行pip install mitmproxy在Windows,但我不断收到拒绝访问,甚至cmdPowerShell使用Run as Administrator选项。

WindowsError: [Error 5] Access is denied: 'c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u\\cryptography-0.9.1\\.eggs\\cffi-1.1.2-py2.7-win-amd64.egg\\_cffi_backend.pyd'

我该如何工作?

I am trying to run pip install mitmproxy on Windows, but I keep getting access denied, even with cmd and PowerShell using the Run as Administrator option.

WindowsError: [Error 5] Access is denied: 'c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u\\cryptography-0.9.1\\.eggs\\cffi-1.1.2-py2.7-win-amd64.egg\\_cffi_backend.pyd'

How can I make this work?


回答 0

如果是Windows,请在cmd中尝试使用python可执行文件运行pip install

例如

python -m pip install mitmproxy

这应该工作,至少对其他软件包安装来说对我有用。

In case of windows, in cmd try to run pip install using python executable

e.g.

python -m pip install mitmproxy

this should work, at least it worked for me for other package installation.


回答 1

通过以下方式更改Python安装文件夹的安全权限:

  1. 打开一个Python shell
  2. 转到任务管理器
  3. 查找python进程
  4. 右键单击并打开位置
  5. 该文件夹将在资源管理器中打开,进入目录
  6. 右键单击该文件夹,然后选择属性
  7. 点击安全标签,然后点击“编辑”
  8. 添加所有人,并授予他们读取和写入的权限。
  9. 保存更改

如果您cmd以管理员身份打开;那么您可以执行以下操作:

如果您的中设置了Python PATH,则:

python -m pip install mitmproxy

Change your Python installation folder’s security permissions by:

  1. Open a Python shell
  2. Go to task manager
  3. Find the python process
  4. Right-click and open location
  5. The folder will open in explorer, go up a directory
  6. Right-click the folder and select properties
  7. Click the security tab and hit ‘edit’
  8. Add everyone and give them permission to Read and Write.
  9. Save your changes

If you open cmd as admin; then you can do the following:

If Python is set in your PATH, then:

python -m pip install mitmproxy

回答 2

我个人发现,以管理员cmd身份打开然后运行 似乎可以解决我的问题。 python -m pip install mitproxy

注意:-我通过以下方式安装了pythonchocolatey

Personally, I found that by opening cmd as admin then run python -m pip install mitproxy seems to fix my problem.

Note:- I installed python through chocolatey


回答 3

以前的答案中未涉及的另一件事,尽管以admin身份运行,但通常会在Windows上引起问题,并且使我无法安装某些软件包,如果有另一个程序使用了某些文件,则会得到相同的权限被拒绝错误。 (要么pip install)尝试访问。这是Windows真正愚蠢的“功能”,它会多次弹出,例如在尝试移动某些文件时。

此外,我不知道如何找出哪个程序锁定了特定文件,因此最简单的方法是在开始任何操作之前,特别是在运行例如Spyder或任何其他基于Python的软件之前,重新引导并进行安装。您也可以尝试关闭所有程序,但是要知道哪个程序实际保存一个文件可能很棘手。例如,对于一个目录,在该目录中打开一个Explorer窗口就足够了。

One additional thing that has not been covered in previous answers and that often cause issues on Windows and stopped me from installing some package despite running as admin is that you get the same permission denied error if there is another program that use some of the files you (or pip install) try to access. This is a really stupid “feature” of Windows that pops up many times, e.g. when trying to move some files.

In addition I have no clue how to figure out which program locks a particular file, so the easiest ting to do is to reboot and do the installation before starting anything, in particular before running e.g. Spyder or any other Python-based software. You can also try to close all programs, but it can be tricky to know which one actually holds a file. For a directory for example, it is enough that you have an Explorer window open at that directory.


回答 4

使用“以管理员身份运行”打开cmd并执行命令pip install mitmproxy。它将安装它。

Open cmd with “Run as administrator” and execute the command pip install mitmproxy. It will install it.


回答 5

因为,我是通过anaconda Prompt安装的。在我的情况下,它甚至都无法使用python -m pip install然后,我添加了这个

python -m pip install <package_name> --user

这个对我有用。

喜欢: python -m pip install "numpy-1.15.4+mkl-cp36-cp36m-win_amd64.whl" --user

请注意,双引号不是必需的,您可以提供要安装的软件包名称。

另一个您应该尝试以“以管理员身份运行”身份运行命令提示符,然后尝试pip安装。它应该工作。

As, i am installing through anaconda Prompt .In my case, it didn’t even work with python -m pip install Then, i add this

python -m pip install <package_name> --user

It works for me.

Like: python -m pip install mitmproxy --user

Another you should try that run the Command Prompt as Run as Administrator and then try pip install. It should work either.


回答 6

尝试授予完全控制python文件夹的权限。

找到python根目录->右键单击->属性->安全->编辑->授予用户完全控制权限->是并等待过程完成。

这个对我有用。

Try to give permission to full control the python folder.

Find the python root directory–>right button click–>properties–>security–>edit–>give users Full Control–>yes and wait the process finished.

It works for me.


回答 7

尝试c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u手动删除文件夹,然后重试pip命令。

Try to delete the folder c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u manually and then retry the pip command.


回答 8

打开命令提示符,因为Administrator仅在不使用Python可执行文件的情况下为我工作。右键单击命令提示符快捷方式,然后选择“以管理员身份运行”。然后运行以下命令。

pip install Django

Opening command prompt As Administrator just worked for me without using Python executable. Right click on command prompt shortcut and choose “Run as Administrator”. Then run the following command.

pip install Django

回答 9

在我的情况下,原因是打开了一个Jupyter笔记本,该笔记本正在导入相关的库。根本原因似乎是Windows错误,原因是该文件处于打开状态/正在使用中(另请参见@Robert的回答以及有关重新启动的建议)。

所以要验证的另一件事是没有其他python进程在运行。

对我来说,关闭笔记本服务器可以解决此问题。

The cause in my case was having a jupyter notebook open, which was importing the relevant library; the root cause seems to be windows error due to the file being open / in use (see also @Robert’s answer, and the recommendation to reboot).

So another thing to verify is that no other python processes are running.

For me, shutting down the notebook server solved the issue.


回答 10

  1. 以管理员身份打开命令提示符。

  2. 要安装任何Python软件包,请使用包括以下命令--user

pip install --ignore-installed --upgrade --user <packagename>

  1. Open Command Prompt as Administrator.

  2. To Install any Python Package use this command including --user.

pip install --ignore-installed --upgrade --user <packagename>


回答 11

当其他所有方法均失败时,请尝试退出您的IDE。我有很多情况都是PyCharm造成的。退出PyCharm之后,我终于能够从命令行安装我的软件包。另外,您也可以通过PyCharm本身在设置->项目:xxx->项目解释器->中进行安装+

When all else fails, try quitting your IDE. I had many cases in which PyCharm was causing this. As soon as I quit PyCharm, I was able to finally install my packages from the command line. Alternatively, you can also install through PyCharm itself in Settings -> Project: xxx -> Project Interpreter -> +.


回答 12

以管理员身份运行cmd.exe,然后键入:

python -m pip install

Run cmd.exe as an administrator then type:

python -m pip install

回答 13

我遇到了类似的问题。但是错误报告是关于

[SSL: TLSV1_ALERT_ACCESS_DENIED] tlsv1 alert access denied (_ssl.c:777)

首先,我尝试了此https://python-forum.io/Thread-All-pip-install-attempts-are-met-with-SSL-error#pid_28035,但似乎无法解决我的问题,仍然重复同样的问题。

其次,如果您在商用计算机上工作,通常它可能存在一个Web内容过滤器(但是我可以直接通过浏览器访问 https://pypi.python.org)。并通过添加代理服务器来解决此问题。

对于Windows,请Internet properties通过IE或Chrome或其他方式打开,然后设置有效的代理地址和端口,这样就可以解决我的问题

或者只是添加该选项pip --proxy [proxy-address]:port install mitmproxy。但是在通过pypi安装时,您始终需要添加此选项。

以上两种解决方案是您需要的替代方案。

I met a similar problem.But the error report is about

[SSL: TLSV1_ALERT_ACCESS_DENIED] tlsv1 alert access denied (_ssl.c:777)

First I tried this https://python-forum.io/Thread-All-pip-install-attempts-are-met-with-SSL-error#pid_28035 ,but seems it couldn’t solve my problems,and still repeat the same issue.

And Second if you are working on a business computer,generally it may exist a web content filter(but I can access https://pypi.python.org through browser directly).And solve this issue by adding a proxy server.

For windows,open the Internet properties through IE or Chrome or whatsoever ,then set valid proxy address and port,and this way solve my problems

Or just adding the option pip --proxy [proxy-address]:port install mitmproxy.But you always need to add this option while installing by pypi

The above two solution is alternative for you demand.


回答 14

就我而言,它甚至无法与 python -m pip install

我所做的是,以管理员身份通过cmd:

PsExec.exe -i -s -d cmd.exe

为了产生SYSTEM cmd,然后 pip install mitmproxy

;)

In my case, it didn’t even work with python -m pip install

What I have done is, from a cmd as administrator:

PsExec.exe -i -s -d cmd.exe

In order to spawn a SYSTEM cmd, then pip install mitmproxy

;)


回答 15

只需关闭所有打开的python文件。并尝试以管理员身份运行。会的。

例如

pip install numpy

Just close all the python files opened. And try to run as administrator. It will work.

e.g.

pip install numpy

使用Python 2.7.3在64位Windows 7上安装Numpy

问题:使用Python 2.7.3在64位Windows 7上安装Numpy

看起来Numpy的唯一64位Windows安装程序适用于Numpy版本1.3.0,仅适用于Python 2.6

http://sourceforge.net/projects/numpy/files/NumPy/

我不得不回滚到Python 2.6才能在Windows上使用Numpy,这让我感到很奇怪,这让我觉得我缺少了一些东西。

是吗

It looks like the only 64 bit windows installer for Numpy is for Numpy version 1.3.0 which only works with Python 2.6

http://sourceforge.net/projects/numpy/files/NumPy/

It strikes me as strange that I would have to roll back to Python 2.6 to use Numpy on Windows, which makes me think I’m missing something.

Am I?


回答 0

在此站点中尝试(非官方)二进制文件:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy

numpy无论有没有针对Python 2.7或Python 3的Intel MKL库,您都可以获取最新的x64。

Try the (unofficial) binaries in this site:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy

You can get the newest numpy x64 with or without Intel MKL libs for Python 2.7 or Python 3.


回答 1

假设您的计算机上安装了python 2.7 64bit,并且已经从此处下载了numpy ,请按照以下步骤操作(numpy‑1.9.2+mkl‑cp27‑none‑win_amd64.whl适当更改)。

  1. get-pip下载(通过右键单击并“保存目标”)到本地驱动器。

  2. 在命令提示,导航到包含目录get-pip.py和运行

    python get-pip.py

    这在创建的文件C:\Python27\Scripts,包括pip2pip2.7pip

  3. 将下载的文件复制numpy‑1.9.2+mkl‑cp27‑none‑win_amd64.whl到上述目录(C:\Python27\Scripts

  4. 仍然在命令提示符下,导航到以上目录并运行:

    pip2.7.exe install "numpy‑1.9.2+mkl‑cp27‑none‑win_amd64.whl"

Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy‑1.9.2+mkl‑cp27‑none‑win_amd64.whl as appropriate).

  1. Download (by right click and “save target”) get-pip to local drive.

  2. At the command prompt, navigate to the directory containing get-pip.py and run

    python get-pip.py

    which creates files in C:\Python27\Scripts, including pip2, pip2.7 and pip.

  3. Copy the downloaded numpy‑1.9.2+mkl‑cp27‑none‑win_amd64.whl into the above directory (C:\Python27\Scripts)

  4. Still at the command prompt, navigate to the above directory and run:

    pip2.7.exe install "numpy‑1.9.2+mkl‑cp27‑none‑win_amd64.whl"


回答 2

http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy下载numpy-1.9.2 + mkl-cp27-none-win32.whl

将文件复制到C:\ Python27 \ Scripts

从上面的位置运行cmd并输入

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

您有望获得以下输出:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

希望对您有用。

编辑1
添加@oneleggedmule的建议:

您也可以在cmd中运行以下命令:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

基本上,单独编写点子也可以很好地工作(与原始答案一样)。为了清晰或明确说明,还可以编写2.7版。

Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .

Copy the file to C:\Python27\Scripts

Run cmd from the above location and type

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

You will hopefully get the below output:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

Hope that works for you.

EDIT 1
Adding @oneleggedmule ‘s suggestion:

You can also run the following command in the cmd:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.


回答 3

(非正式)二进制文件(http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy) 为我工作。
我尝试过Mingw,Cygwin,但由于各种原因都失败了。我使用的是Windows 7 Enterprise(64位)。

The (unofficial) binaries (http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy) worked for me.
I’ve tried Mingw, Cygwin, all failed due to varies reasons. I am on Windows 7 Enterprise, 64bit.


回答 4

您也可以尝试这样做,Python http://continuum.io/downloads

但是您需要修改环境变量PATH,以使anaconda文件夹位于原始Python文件夹之前。

You may also try this, anaconda http://continuum.io/downloads

But you need to modify your environment variable PATH, so that the anaconda folder is before the original Python folder.


回答 5

并非不可能,程序员在Windows上寻找python,也使用适用于Visual Studio的Python工具。在这种情况下,可以利用附带的“ Python环境”窗口轻松安装其他软件包。默认情况下,在窗口中选择“概述”。您可以在那里选择“点子”。

然后,您可以通过在seach窗口中输入numpy来安装numpy,而无需进行其他工作。已经建议使用核心响应的“安装numpy”指令。

不过,一开始我有2个容易解决的问题:

  • “错误:无法找到vcvarsall.bat”:此问题已在此处解决。尽管我当时没有找到它,而是安装了PythonC ++编译器
  • 然后,安装继续,但由于其他内部异常而失败。安装.NET 3.5可以解决此问题。

最终安装完成。这花了一些时间(5分钟),所以不要提早取消该过程。

It is not improbable, that programmers looking for python on windows, also use the Python Tools for Visual Studio. In this case it is easy to install additional packages, by taking advantage of the included “Python Environment” Window. “Overview” is selected within the window as default. You can select “Pip” there.

Then you can install numpy without additional work by entering numpy into the seach window. The coresponding “install numpy” instruction is already suggested.

Nevertheless I had 2 easy to solve Problems in the beginning:

  • “error: Unable to find vcvarsall.bat”: This problem has been solved here. Although I did not find it at that time and instead installed the C++ Compiler for Python.
  • Then the installation continued but failed because of an additional inner exception. Installing .NET 3.5 solved this.

Finally the installation was done. It took some time (5 minutes), so don’t cancel the process to early.