标签归档:path

在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的相对位置打开文件

假设python代码在以前的Windows目录“ main”中未知的位置执行,并且在运行时将代码安装在任何地方,都需要访问目录“ main / 2091 / data.txt”。

我应该如何使用open(location)函数?应该在什么位置?

编辑:

我发现下面的简单代码可以工作..它有什么缺点吗?

    file="\2091\sample.txt"
    path=os.getcwd()+file
    fp=open(path,'r+');

Suppose python code is executed in not known by prior windows directory say ‘main’ , and wherever code is installed when it runs it needs to access to directory ‘main/2091/data.txt’ .

how should I use open(location) function? what should be location ?

Edit :

I found that below simple code will work..does it have any disadvantages ?

    file="\2091\sample.txt"
    path=os.getcwd()+file
    fp=open(path,'r+');

回答 0

使用这种类型的东西时,您需要注意实际的工作目录是什么。例如,您可能无法从文件所在的目录中运行脚本。在这种情况下,您不能仅使用相对路径本身。

如果确定所需文件位于脚本实际所在的子目录中,则可以__file__在此处使用帮助。 __file__是您正在运行的脚本所在的完整路径。

因此,您可以摆弄这样的东西:

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can’t just use a relative path by itself.

If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located.

So you can fiddle with something like this:

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

回答 1

这段代码可以正常工作:

import os


def readFile(filename):
    filehandle = open(filename)
    print filehandle.read()
    filehandle.close()



fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)

This code works fine:

import os


def readFile(filename):
    filehandle = open(filename)
    print filehandle.read()
    filehandle.close()



fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)

回答 2

我创建一个帐户只是为了澄清我认为在Russ原始回复中发现的差异。

作为参考,他的原始答案是:

import os
script_dir = os.path.dirname(__file__)
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

这是一个很好的答案,因为它试图动态创建所需文件的绝对系统路径。

Cory Mawhorter注意到这__file__是相对路径(在我的系统上也是这样),建议使用os.path.abspath(__file__)os.path.abspath,但是,返回当前脚本的绝对路径(即/path/to/dir/foobar.py

要使用此方法(以及我最终如何使用它),必须从路径末尾删除脚本名称:

import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] #i.e. /path/to/dir/
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

所得的abs_file_path(在此示例中)变为: /path/to/dir/2091/data.txt

I created an account just so I could clarify a discrepancy I think I found in Russ’s original response.

For reference, his original answer was:

import os
script_dir = os.path.dirname(__file__)
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

This is a great answer because it is trying to dynamically creates an absolute system path to the desired file.

Cory Mawhorter noticed that __file__ is a relative path (it is as well on my system) and suggested using os.path.abspath(__file__). os.path.abspath, however, returns the absolute path of your current script (i.e. /path/to/dir/foobar.py)

To use this method (and how I eventually got it working) you have to remove the script name from the end of the path:

import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] #i.e. /path/to/dir/
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

The resulting abs_file_path (in this example) becomes: /path/to/dir/2091/data.txt


回答 3

这取决于您使用的操作系统。如果您想要一个与Windows和* nix兼容的解决方案,例如:

from os import path

file_path = path.relpath("2091/data.txt")
with open(file_path) as f:
    <do stuff>

应该工作正常。

path模块能够格式化其正在运行的任何操作系统的路径。另外,只要您具有正确的权限,python就能很好地处理相对路径。

编辑

正如kindall在评论中提到的那样,python仍然可以在unix样式和Windows样式路径之间进行转换,因此,即使是更简单的代码也可以使用:

with open("2091/data/txt") as f:
    <do stuff>

话虽如此,该path模块仍然具有一些有用的功能。

It depends on what operating system you’re using. If you want a solution that is compatible with both Windows and *nix something like:

from os import path

file_path = path.relpath("2091/data.txt")
with open(file_path) as f:
    <do stuff>

should work fine.

The path module is able to format a path for whatever operating system it’s running on. Also, python handles relative paths just fine, so long as you have correct permissions.

Edit:

As mentioned by kindall in the comments, python can convert between unix-style and windows-style paths anyway, so even simpler code will work:

with open("2091/data/txt") as f:
    <do stuff>

That being said, the path module still has some useful functions.


回答 4

我花了很多时间发现为什么我的代码找不到在Windows系统上运行Python 3的文件。所以我加了。之前/一切正常:

import os

script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, './output03.txt')
print(file_path)
fptr = open(file_path, 'w')

I spend a lot time to discover why my code could not find my file running Python 3 on the Windows system. So I added . before / and everything worked fine:

import os

script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, './output03.txt')
print(file_path)
fptr = open(file_path, 'w')

回答 5

码:

import os
script_path = os.path.abspath(__file__) 
path_list = script_path.split(os.sep)
script_directory = path_list[0:len(path_list)-1]
rel_path = "main/2091/data.txt"
path = "/".join(script_directory) + "/" + rel_path

说明:

导入库:

import os

用于__file__获取当前脚本的路径:

script_path = os.path.abspath(__file__)

将脚本路径分为多个项目:

path_list = script_path.split(os.sep)

删除列表中的最后一项(实际的脚本文件):

script_directory = path_list[0:len(path_list)-1]

添加相对文件的路径:

rel_path = "main/2091/data.txt

加入列表项,并添加相对路径的文件:

path = "/".join(script_directory) + "/" + rel_path

现在,您可以设置要对文件执行的任何操作,例如:

file = open(path)

Code:

import os
script_path = os.path.abspath(__file__) 
path_list = script_path.split(os.sep)
script_directory = path_list[0:len(path_list)-1]
rel_path = "main/2091/data.txt"
path = "/".join(script_directory) + "/" + rel_path

Explanation:

Import library:

import os

Use __file__ to attain the current script’s path:

script_path = os.path.abspath(__file__)

Separates the script path into multiple items:

path_list = script_path.split(os.sep)

Remove the last item in the list (the actual script file):

script_directory = path_list[0:len(path_list)-1]

Add the relative file’s path:

rel_path = "main/2091/data.txt

Join the list items, and addition the relative path’s file:

path = "/".join(script_directory) + "/" + rel_path

Now you are set to do whatever you want with the file, such as, for example:

file = open(path)

回答 6

如果文件在您的父文件夹中,例如。follower.txt,您可以简单地使用open('../follower.txt', 'r').read()

If the file is in your parent folder, eg. follower.txt, you can simply use open('../follower.txt', 'r').read()


回答 7

试试这个:

from pathlib import Path

data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"

f = open(file_to_open)

print(f.read())

Python 3.4引入了一个新的用于处理文件和路径的标准库,称为pathlib。这个对我有用!

Try this:

from pathlib import Path

data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"

f = open(file_to_open)

print(f.read())

Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!


回答 8

不确定是否到处都能使用。

我在ubuntu中使用ipython。

如果要读取当前文件夹的子目录中的文件:

/current-folder/sub-directory/data.csv

您的脚本在当前文件夹中,只需尝试以下操作:

import pandas as pd
path = './sub-directory/data.csv'
pd.read_csv(path)

Not sure if this work everywhere.

I’m using ipython in ubuntu.

If you want to read file in current folder’s sub-directory:

/current-folder/sub-directory/data.csv

your script is in current-folder simply try this:

import pandas as pd
path = './sub-directory/data.csv'
pd.read_csv(path)

回答 9

Python只是将您提供的文件名传递给操作系统,然后将其打开。如果您的操作系统支持相对路径main/2091/data.txt(如:提示),则可以正常工作。

您可能会发现,回答此类问题的最简单方法是尝试一下,看看会发生什么。

Python just passes the filename you give it to the operating system, which opens it. If your operating system supports relative paths like main/2091/data.txt (hint: it does), then that will work fine.

You may find that the easiest way to answer a question like this is to try it and see what happens.


回答 10

import os
def file_path(relative_path):
    dir = os.path.dirname(os.path.abspath(__file__))
    split_path = relative_path.split("/")
    new_path = os.path.join(dir, *split_path)
    return new_path

with open(file_path("2091/data.txt"), "w") as f:
    f.write("Powerful you have become.")
import os
def file_path(relative_path):
    dir = os.path.dirname(os.path.abspath(__file__))
    split_path = relative_path.split("/")
    new_path = os.path.join(dir, *split_path)
    return new_path

with open(file_path("2091/data.txt"), "w") as f:
    f.write("Powerful you have become.")

回答 11

当我还是初学者时,我发现这些描述有些令人生畏。一开始我会尝试 For Windows

f= open('C:\Users\chidu\Desktop\Skipper New\Special_Note.txt','w+')
print(f) 

这将引发一个syntax error。我曾经很困惑。然后在Google上进行一些冲浪之后。找到了发生错误的原因。写给初学者

这是因为要以Unicode读取路径,您只需\在启动文件路径时添加一个

f= open('C:\\Users\chidu\Desktop\Skipper New\Special_Note.txt','w+')
print(f)

现在,它可以\在启动目录之前添加。

When I was a beginner I found these descriptions a bit intimidating. As at first I would try For Windows

f= open('C:\Users\chidu\Desktop\Skipper New\Special_Note.txt','w+')
print(f) 

and this would raise an syntax error. I used get confused alot. Then after some surfing across google. found why the error occurred. Writing this for beginners

It’s because for path to be read in Unicode you simple add a \ when starting file path

f= open('C:\\Users\chidu\Desktop\Skipper New\Special_Note.txt','w+')
print(f)

And now it works just add \ before starting the directory.


如何获取父目录位置

问题:如何获取父目录位置

这段代码是在b.py中获取templates / blog1 / page.html:

path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html'))

但我想获取父目录位置:

aParent
   |--a
   |  |---b.py
   |      |---templates
   |              |--------blog1
   |                         |-------page.html
   |--templates
          |--------blog1
                     |-------page.html

以及如何获取父位置

谢谢

更新:

这是对的:

dirname=os.path.dirname
path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))

要么

path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))

this code is get the templates/blog1/page.html in b.py:

path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html'))

but i want to get the parent dir location:

aParent
   |--a
   |  |---b.py
   |      |---templates
   |              |--------blog1
   |                         |-------page.html
   |--templates
          |--------blog1
                     |-------page.html

and how to get the aParent location

thanks

updated:

this is right:

dirname=os.path.dirname
path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))

or

path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))

回答 0

您可以重复应用dirname来爬高:dirname(dirname(file))。但是,这只能到达根包。如果有问题,请使用os.path.abspathdirname(dirname(abspath(file)))

You can apply dirname repeatedly to climb higher: dirname(dirname(file)). This can only go as far as the root package, however. If this is a problem, use os.path.abspath: dirname(dirname(abspath(file))).


回答 1

os.path.abspath不会验证任何内容,因此,如果我们已经向其追加字符串,__file__则无需理会dirname或加入其中的任何一个。只需将其__file__视为目录并开始爬山:

# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")

这远不os.path.abspath(os.path.join(os.path.dirname(__file__),".."))及易处理dirname(dirname(__file__))。攀登两个以上的水平开始变得荒谬。

但是,由于我们知道要爬多少层,我们可以用一个简单的小函数来清理它:

uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])

# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'

os.path.abspath doesn’t validate anything, so if we’re already appending strings to __file__ there’s no need to bother with dirname or joining or any of that. Just treat __file__ as a directory and start climbing:

# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")

That’s far less convoluted than os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) and about as manageable as dirname(dirname(__file__)). Climbing more than two levels starts to get ridiculous.

But, since we know how many levels to climb, we could clean this up with a simple little function:

uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])

# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'

回答 2

相对路径pathlibPython 3.4+中的模块一起使用:

from pathlib import Path

Path(__file__).parent

您可以使用多个调用来parent进一步进行以下操作:

Path(__file__).parent.parent

作为指定parent两次的替代方法,可以使用:

Path(__file__).parents[1]

Use relative path with the pathlib module in Python 3.4+:

from pathlib import Path

Path(__file__).parent

You can use multiple calls to parent to go further in the path:

Path(__file__).parent.parent

As an alternative to specifying parent twice, you can use:

Path(__file__).parents[1]

回答 3

os.path.dirname(os.path.abspath(__file__))

应该给你通往的道路a

但是,如果b.py当前执行的是文件,则只需执行以下操作即可

os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))
os.path.dirname(os.path.abspath(__file__))

Should give you the path to a.

But if b.py is the file that is currently executed, then you can achieve the same by just doing

os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))

回答 4

os.pardir是一种更好的方法../,更具可读性。

import os
print os.path.abspath(os.path.join(given_path, os.pardir))  

这将返回给定路径的父路径

os.pardir is a better way for ../ and more readable.

import os
print os.path.abspath(os.path.join(given_path, os.pardir))  

This will return the parent path of the given_path


回答 5

一种简单的方法可以是:

import os
current_dir =  os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir

A simple way can be:

import os
current_dir =  os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir

回答 6

可能是加入两个..文件夹,以获取父文件夹的父文件夹?

path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))

May be join two .. folder, to get parent of the parent folder?

path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))

回答 7

使用以下命令跳到上一个文件夹:

os.chdir(os.pardir)

如果您需要多次跳转,那么在这种情况下,使用简单的装饰器是一个好而简单的解决方案。

Use the following to jump to previous folder:

os.chdir(os.pardir)

If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.


回答 8

这是另一个相对简单的解决方案:

  • 不使用dirname()(在“ file.txt”这样的一级参数或“ ..”这样的相对父级上不能按预期工作)
  • 不使用abspath()(避免对当前工作目录进行任何假设),而是保留路径的相对字符

它只是使用normpathjoin

def parent(p):
    return os.path.normpath(os.path.join(p, os.path.pardir))

# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
        'dir/file.txt', '../up/', '/abs/path']:
    print parent(p)

结果:

.
foo/bar
with/trailing
dir
..
/abs

Here is another relatively simple solution that:

  • does not use dirname() (which does not work as expected on one level arguments like “file.txt” or relative parents like “..”)
  • does not use abspath() (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths

it just uses normpath and join:

def parent(p):
    return os.path.normpath(os.path.join(p, os.path.pardir))

# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
        'dir/file.txt', '../up/', '/abs/path']:
    print parent(p)

Result:

.
foo/bar
with/trailing
dir
..
/abs

回答 9

我认为用这个更好:

os.path.realpath(__file__).rsplit('/', X)[0]


In [1]: __file__ = "/aParent/templates/blog1/page.html"

In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'

In [4]: __file__ = "/aParent/templates/blog1/page.html"

In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'

In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'

In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'

I think use this is better:

os.path.realpath(__file__).rsplit('/', X)[0]


In [1]: __file__ = "/aParent/templates/blog1/page.html"

In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'

In [4]: __file__ = "/aParent/templates/blog1/page.html"

In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'

In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'

In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'

回答 10

我试过了:

import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))

I tried:

import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))

Python列表目录,子目录和文件

问题:Python列表目录,子目录和文件

我试图制作一个脚本来列出给定目录中的所有目录,子目录和文件。
我尝试了这个:

import sys,os

root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")

for r,d,f in os.walk(path):
    for file in f:
        print os.path.join(root,file)

不幸的是,它无法正常工作。
我得到所有文件,但没有完整的路径。

例如,如果dir结构为:

/home/patate/directory/targetdirectory/123/456/789/file.txt

它会打印:

/home/patate/directory/targetdirectory/file.txt

我需要的是第一个结果。任何帮助将不胜感激!谢谢。

I’m trying to make a script to list all directory, subdirectory, and files in a given directory.
I tried this:

import sys,os

root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")

for r,d,f in os.walk(path):
    for file in f:
        print os.path.join(root,file)

Unfortunatly it doesn’t work properly.
I get all the files, but not their complete paths.

For example if the dir struct would be:

/home/patate/directory/targetdirectory/123/456/789/file.txt

It would print:

/home/patate/directory/targetdirectory/file.txt

What I need is the first result. Any help would be greatly appreciated! Thanks.


回答 0

使用os.path.join来连接的目录和文件

for path, subdirs, files in os.walk(root):
    for name in files:
        print os.path.join(path, name)

请注意,path并没有root在串联中使用,因为使用root会不正确。


在Python 3.4中,添加了pathlib模块以简化路径操作。因此,等效于os.path.join

pathlib.PurePath(path, name)

好处pathlib是您可以在路径上使用各种有用的方法。如果使用具体的Path变体,您还可以通过它们进行实际的OS调用,例如,进入目录,删除路径,打开其指向的文件等等。

Use os.path.join to concatenate the directory and file name:

for path, subdirs, files in os.walk(root):
    for name in files:
        print os.path.join(path, name)

Note the usage of path and not root in the concatenation, since using root would be incorrect.


In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join would be:

pathlib.PurePath(path, name)

The advantage of pathlib is that you can use a variety of useful methods on paths. If you use the concrete Path variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.


回答 1

以防万一…获取目录和子目录中与某个模式匹配的所有文件(例如* .py):

import os
from fnmatch import fnmatch

root = '/some/directory'
pattern = "*.py"

for path, subdirs, files in os.walk(root):
    for name in files:
        if fnmatch(name, pattern):
            print os.path.join(path, name)

Just in case… Getting all files in the directory and subdirectories matching some pattern (*.py for example):

import os
from fnmatch import fnmatch

root = '/some/directory'
pattern = "*.py"

for path, subdirs, files in os.walk(root):
    for name in files:
        if fnmatch(name, pattern):
            print os.path.join(path, name)

回答 2

这里是单线:

import os

[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text

最外面的val for sublist in ...循环将列表平整为一维。该j循环收集每个文件名前缀的列表,并将其加入到当前的路径。最后,i循环遍历所有目录和子目录。

本示例./os.walk(...)调用中使用了硬编码的路径,您可以补充所需的任何路径字符串。

注意:os.path.expanduser和/或os.path.expandvars可用于路径字符串,例如~/

扩展此示例:

它易于添加文件基本名测试和目录名测试。

例如,测试*.jpg文件:

... for j in i[2] if j.endswith('.jpg')] ...

此外,排除.git目录:

... for i in os.walk('./') if '.git' not in i[0].split('/')]

Here is a one-liner:

import os

[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text

The outer most val for sublist in ... loop flattens the list to be one dimensional. The j loop collects a list of every file basename and joins it to the current path. Finally, the i loop iterates over all directories and sub directories.

This example uses the hard-coded path ./ in the os.walk(...) call, you can supplement any path string you like.

Note: os.path.expanduser and/or os.path.expandvars can be used for paths strings like ~/

Extending this example:

Its easy to add in file basename tests and directoryname tests.

For Example, testing for *.jpg files:

... for j in i[2] if j.endswith('.jpg')] ...

Additionally, excluding the .git directory:

... for i in os.walk('./') if '.git' not in i[0].split('/')]

回答 3

无法发表评论,请在此处写答案。这是我所看到的最清晰的一行:

import os
[os.path.join(path, name) for path, subdirs, files in os.walk(root) for name in files]

Couldn’t comment so writing answer here. This is the clearest one-line I have seen:

import os
[os.path.join(path, name) for path, subdirs, files in os.walk(root) for name in files]

回答 4

您可以看一下我制作的这个样本。它使用了os.path.walk函数,该函数已被提倡,使用列表存储所有文件路径

root = "Your root directory"
ex = ".txt"
where_to = "Wherever you wanna write your file to"
def fileWalker(ext,dirname,names):
    '''
    checks files in names'''
    pat = "*" + ext[0]
    for f in names:
        if fnmatch.fnmatch(f,pat):
            ext[1].append(os.path.join(dirname,f))


def writeTo(fList):

    with open(where_to,"w") as f:
        for di_r in fList:
            f.write(di_r + "\n")






if __name__ == '__main__':
    li = []
    os.path.walk(root,fileWalker,[ex,li])

    writeTo(li)

You can take a look at this sample I made. It uses the os.path.walk function which is deprecated beware.Uses a list to store all the filepaths

root = "Your root directory"
ex = ".txt"
where_to = "Wherever you wanna write your file to"
def fileWalker(ext,dirname,names):
    '''
    checks files in names'''
    pat = "*" + ext[0]
    for f in names:
        if fnmatch.fnmatch(f,pat):
            ext[1].append(os.path.join(dirname,f))


def writeTo(fList):

    with open(where_to,"w") as f:
        for di_r in fList:
            f.write(di_r + "\n")






if __name__ == '__main__':
    li = []
    os.path.walk(root,fileWalker,[ex,li])

    writeTo(li)

回答 5

一线简单一点:

import os
from itertools import product, chain

chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])

A bit simpler one-liner:

import os
from itertools import product, chain

chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])

回答 6

由于这里的每个示例都仅使用walk(with join),因此我想展示一个不错的示例并与进行比较listdir

import os, time

def listFiles1(root): # listdir
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0)+"/"; items = os.listdir(folder) # items = folders + files
        for i in items: i=folder+i; (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles2(root): # listdir/join (takes ~1.4x as long) (and uses '\\' instead)
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0); items = os.listdir(folder) # items = folders + files
        for i in items: i=os.path.join(folder,i); (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles3(root): # walk (takes ~1.5x as long)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[folder.replace("\\","/")+"/"+file] # folder+"\\"+file still ~1.5x
    return allFiles

def listFiles4(root): # walk/join (takes ~1.6x as long) (and uses '\\' instead)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[os.path.join(folder,file)]
    return allFiles


for i in range(100): files = listFiles1("src") # warm up

start = time.time()
for i in range(100): files = listFiles1("src") # listdir
print("Time taken: %.2fs"%(time.time()-start)) # 0.28s

start = time.time()
for i in range(100): files = listFiles2("src") # listdir and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.38s

start = time.time()
for i in range(100): files = listFiles3("src") # walk
print("Time taken: %.2fs"%(time.time()-start)) # 0.42s

start = time.time()
for i in range(100): files = listFiles4("src") # walk and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.47s

因此,如您所见,该listdir版本效率更高。(那join很慢)

Since every example here is just using walk (with join), i’d like to show a nice example and comparison with listdir:

import os, time

def listFiles1(root): # listdir
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0)+"/"; items = os.listdir(folder) # items = folders + files
        for i in items: i=folder+i; (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles2(root): # listdir/join (takes ~1.4x as long) (and uses '\\' instead)
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0); items = os.listdir(folder) # items = folders + files
        for i in items: i=os.path.join(folder,i); (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles3(root): # walk (takes ~1.5x as long)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[folder.replace("\\","/")+"/"+file] # folder+"\\"+file still ~1.5x
    return allFiles

def listFiles4(root): # walk/join (takes ~1.6x as long) (and uses '\\' instead)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[os.path.join(folder,file)]
    return allFiles


for i in range(100): files = listFiles1("src") # warm up

start = time.time()
for i in range(100): files = listFiles1("src") # listdir
print("Time taken: %.2fs"%(time.time()-start)) # 0.28s

start = time.time()
for i in range(100): files = listFiles2("src") # listdir and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.38s

start = time.time()
for i in range(100): files = listFiles3("src") # walk
print("Time taken: %.2fs"%(time.time()-start)) # 0.42s

start = time.time()
for i in range(100): files = listFiles4("src") # walk and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.47s

So as you can see for yourself, the listdir version is much more efficient. (and that join is slow)


在ipython中运行python脚本

问题:在ipython中运行python脚本

是否可以从ipython内部运行python脚本(而不是模块)而不指示其路径?我尝试设置PYTHONPATH,但它似乎仅适用于模块。我想执行

%run my_script.py

而不在包含文件的目录中。

Is it possible to run a python script (not module) from inside ipython without indicating its path? I tried to set PYTHONPATH but it seems to work only for modules. I would like to execute

%run my_script.py

without being in the directory containing the file.


回答 0

从“ my_script.py”目录中,您可以简单地执行以下操作:

%run ./my_script.py

from within the directory of “my_script.py” you can simply do:

%run ./my_script.py

回答 1

如何在Ipython中运行脚本

import os
filepath='C:\\Users\\User\\FolderWithPythonScript' 
os.chdir(filepath)
%run pyFileInThatFilePath.py

那应该做

How to run a script in Ipython

import os
filepath='C:\\Users\\User\\FolderWithPythonScript' 
os.chdir(filepath)
%run pyFileInThatFilePath.py

That should do it


回答 2

%run魔术有一个参数file_finder,它使用来获取完整路径文件来执行(见这里); 如您所述,它只是在当前目录中查找,如有必要,附加“ .py”。

似乎没有要到指定的文件取景器使用方式,从%run魔术,但没有什么可以从定义自己的魔法命令阻止你在调用%run用适当的文件查找。

作为一个非常讨厌的黑客,您可以file_finder使用自己的默认设置覆盖默认设置:

IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder

坦白地说,按照IPython API的变化速度,它与定义您自己的魔术一样可能继续起作用。

The %run magic has a parameter file_finder that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending “.py” if necessary.

There doesn’t seem to be a way to specify which file finder to use from the %run magic, but there’s nothing to stop you from defining your own magic command that calls into %run with an appropriate file finder.

As a very nasty hack, you could override the default file_finder with your own:

IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder

To be honest, at the rate the IPython API is changing that’s as likely to continue to work as defining your own magic is.


回答 3

在python中,模块和脚本之间没有区别;您可以同时执行脚本和模块。该文件必须位于pythonpath AFAIK上,因为python必须能够找到有问题的文件。如果从目录执行python,则该目录会自动添加到pythonpath中。

请参阅什么是从另一个Python脚本调用Python脚本的最佳方法?有关模块和脚本的更多信息

还有一个内置函数execfile(filename)将执行您想要的操作

In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.

Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts

There is also a builtin function execfile(filename) that will do what you want


回答 4

适用于Python 3.6.5

import os
os.getcwd()
runfile('testing.py')

for Python 3.6.5

import os
os.getcwd()
runfile('testing.py')

如何从Python的文件路径中提取文件夹路径?

问题:如何从Python的文件路径中提取文件夹路径?

我只想从完整路径到文件获取文件夹路径。

例如T:\Data\DBDesign\DBDesign_93_v141b.mdb,我想要得到T:\Data\DBDesign(不包括\DBDesign_93_v141b.mdb)。

我已经尝试过这样的事情:

existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = str(existGDBPath.split('\\')[0:-1])
print wkspFldr 

但是它给了我这样的结果:

['T:', 'Data', 'DBDesign']

这不是我需要的结果(为T:\Data\DBDesign)。

关于如何获取文件路径的任何想法?

I would like to get just the folder path from the full path to a file.

For example T:\Data\DBDesign\DBDesign_93_v141b.mdb and I would like to get just T:\Data\DBDesign (excluding the \DBDesign_93_v141b.mdb).

I have tried something like this:

existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = str(existGDBPath.split('\\')[0:-1])
print wkspFldr 

but it gave me a result like this:

['T:', 'Data', 'DBDesign']

which is not the result that I require (being T:\Data\DBDesign).

Any ideas on how I can get the path to my file?


回答 0

您几乎可以使用该split功能了。您只需要加入字符串,如下所示。

>>> import os
>>> '\\'.join(existGDBPath.split('\\')[0:-1])
'T:\\Data\\DBDesign'

虽然,我建议使用该os.path.dirname函数来执行此操作,但是您只需要传递字符串即可,它将为您完成工作。由于您似乎在Windows上,因此也考虑使用该abspath功能。一个例子:

>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
'T:\\Data\\DBDesign'

如果要在拆分后同时需要文件名和目录路径,则可以使用os.path.split返回元组的函数,如下所示。

>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\\Data\\DBDesign', 'DBDesign_93_v141b.mdb')

You were almost there with your use of the split function. You just needed to join the strings, like follows.

>>> import os
>>> '\\'.join(existGDBPath.split('\\')[0:-1])
'T:\\Data\\DBDesign'

Although, I would recommend using the os.path.dirname function to do this, you just need to pass the string, and it’ll do the work for you. Since, you seem to be on windows, consider using the abspath function too. An example:

>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
'T:\\Data\\DBDesign'

If you want both the file name and the directory path after being split, you can use the os.path.split function which returns a tuple, as follows.

>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\\Data\\DBDesign', 'DBDesign_93_v141b.mdb')

回答 1

带有PATHLIB模块(更新后的答案)

人们应该考虑使用pathlib进行新开发。它在适用于Python3.4的stdlib中,但在PyPI上可用于早期版本。该库提供了一种更面向对象的方法来操作路径<opinion>,并且使用更加容易阅读和编程</opinion>

>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')

使用OS模块

使用os.path模块:

>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:\Data\DBDesign'

您可以继续假设,如果您需要进行某种文件名操作,则已经在中实现了os.path。如果没有,您可能仍需要将此模块用作构建模块。

WITH PATHLIB MODULE (UPDATED ANSWER)

One should consider using pathlib for new development. It is in the stdlib for Python3.4, but available on PyPI for earlier versions. This library provides a more object-orented method to manipulate paths <opinion> and is much easier read and program with </opinion>.

>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')

WITH OS MODULE

Use the os.path module:

>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:\Data\DBDesign'

You can go ahead and assume that if you need to do some sort of filename manipulation it’s already been implemented in os.path. If not, you’ll still probably need to use this module as the building block.


回答 2

内置子模块os.path具有用于该任务的功能。

import os
os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb')

The built-in submodule os.path has a function for that very task.

import os
os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb')

回答 3

这是代码:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

Here is the code:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

回答 4

这是我的小实用程序帮助程序,用于拆分路径int文件和路径标记:

import os    
# usage: file, path = splitPath(s)
def splitPath(s):
    f = os.path.basename(s)
    p = s[:-(len(f))-1]
    return f, p

Here is my little utility helper for splitting paths int file, path tokens:

import os    
# usage: file, path = splitPath(s)
def splitPath(s):
    f = os.path.basename(s)
    p = s[:-(len(f))-1]
    return f, p

回答 5

任何在ESRI GIS Table字段计算器界面中尝试执行此操作的人都可以使用Python解析器执行此操作:

PathToContainingFolder =

"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])

以便

\ Users \ me \ Desktop \ New文件夹\ file.txt

变成

\ Users \ me \ Desktop \ New文件夹

Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:

PathToContainingFolder =

"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])

so that

\Users\me\Desktop\New folder\file.txt

becomes

\Users\me\Desktop\New folder


ImportError:DLL加载失败:%1不是有效的Win32应用程序。但是DLL在那里

问题:ImportError:DLL加载失败:%1不是有效的Win32应用程序。但是DLL在那里

我的情况非常类似于ImportError上的情况:DLL加载失败:%1不是有效的Win32应用程序,但是答案对我不起作用。

我的Python代码说:

import cv2

但是该行引发了此问题标题中显示的错误。

C:\lib\opencv在这台64位计算机上安装了OpenCV 。我正在使用64位Python。

我的PYTHONPATH变量:PYTHONPATH=C:\lib\opencv\build\python\2.7。该文件夹包含cv2.pyd所有内容。

我的PATH变量:Path=%OPENCV_DIR%\bin;...此文件夹包含39个DLL文件,例如opencv_core246d.dll

OPENCV_DIR具有以下值:OPENCV_DIR=C:\lib\opencv\build\x64\vc11

ImportError上的解决方案:DLL加载失败:%1不是有效的Win32应用程序,表示要向C:\opencv\build\bin\ReleaseWindows PATH环境变量添加新的opencv二进制路径()。但是,如上所示,C:\lib\opencv\build\x64\vc11\bin我的PATH中已经有OpenCV Binaries文件夹()。而且我的OpenCV安装没有任何Release文件夹(build / java下为空)。

关于出什么问题有什么想法吗?我可以告诉Python详细跟踪加载过程吗?究竟要寻找什么DLL?

谢谢,拉斯

编辑:

我只注意到,根据http://www.dependencywalker.com/中,cv2.pydC:\lib\opencv\build\python\2.7为32位,而我运行的机器和Python的是64位。可能是问题所在吗?如果是这样,我在哪里可以找到cv2.pyd的64位版本?

I have a situation very much like the one at ImportError: DLL load failed: %1 is not a valid Win32 application, but the answer there isn’t working for me.

My Python code says:

import cv2

But that line throws the error shown in the title of this question.

I have OpenCV installed in C:\lib\opencv on this 64-bit machine. I’m using 64-bit Python.

My PYTHONPATH variable: PYTHONPATH=C:\lib\opencv\build\python\2.7. This folder contains cv2.pyd and that’s all.

My PATH variable: Path=%OPENCV_DIR%\bin;... This folder contains 39 DLL files such as opencv_core246d.dll.

OPENCV_DIR has this value: OPENCV_DIR=C:\lib\opencv\build\x64\vc11.

The solution at ImportError: DLL load failed: %1 is not a valid Win32 application says to add “the new opencv binaries path (C:\opencv\build\bin\Release) to the Windows PATH environment variable”. But as shown above, I already have the OpenCV binaries folder (C:\lib\opencv\build\x64\vc11\bin) in my PATH. And my OpenCV installation doesn’t have any Release folders (except for an empty one under build/java).

Any ideas as to what’s going wrong? Can I tell Python to verbosely trace the loading process? Exactly what DLL’s is it looking for?

Thanks, Lars

EDIT:

I just noticed that, according to http://www.dependencywalker.com/, the cv2.pyd in C:\lib\opencv\build\python\2.7 is 32-bit, whereas the machine and the Python I’m running are 64-bit. Could that be the problem? And if so, where can I find a 64-bit version of cv2.pyd?


回答 0


回答 1

请检查您使用的python版本是否也是64位。如果没有,那可能就是问题所在。您将使用32位python版本,并且已为OPENCV库安装了64位二进制文​​件。

Please check if the python version you are using is also 64 bit. If not then that could be the issue. You would be using a 32 bit python version and would have installed a 64 bit binaries for the OPENCV library.


回答 2

哇,我发现了这个问题的另一种情况。以上都不起作用。最终,我使用python的功能来内省正在加载的内容。对于python 2.7,这意味着:

import imp
imp.find_module("cv2")

这在Anaconda DLL目录中打开了一个完全意外的“ cv2.pyd”文件,多次卸载/安装尝试均未涉及该文件。Python首先是在那儿寻找的,却找不到我的好安装。我删除了该cv2.pyd文件,然后再次尝试imp.find_module(“ cv2”),python立即找到了正确的文件,并且cv2开始工作。

因此,如果没有其他解决方案对您有用,请确保您使用python内省来查看python尝试加载的文件。

Wow, I found yet another case for this problem. None of the above worked. Eventually I used python’s ability to introspect what was being loaded. For python 2.7 this means:

import imp
imp.find_module("cv2")

This turned up a completely unexpected “cv2.pyd” file in an Anaconda DLL directory that wasn’t touched by multiple uninstall/install attempts. Python was looking there first and not finding my good installation. I deleted that cv2.pyd file and tried imp.find_module(“cv2”) again and python immediately found the right file and cv2 started working.

So if none of the other solutions work for you, make sure you use python introspection to see what file python is trying to load.


回答 3

就我而言,我有64位python,而lxml是错误的版本-我也应该一直使用x64版本。我通过在此处下载lxml的64位版本来解决此问题:

https://pypi.python.org/pypi/lxml/3.4.1

lxml-3.4.1.win-amd64-py2.7.exe

这是一个令人沮丧的问题的最简单答案。

In my case, I have 64bit python, and it was lxml that was the wrong version–I should have been using the x64 version of that as well. I solved this by downloading the 64-bit version of lxml here:

https://pypi.python.org/pypi/lxml/3.4.1

lxml-3.4.1.win-amd64-py2.7.exe

This was the simplest answer to a frustrating issue.


回答 4

我只是遇到了这个问题,原来是因为我使用的是x64版本的opencv文件。尝试了x86,它起作用了。

I just had this problem, it turns it was just because I was using x64 version of the opencv file. Tried the x86 and it worked.


回答 5

如果您的构建系统(在我的情况下为CMake)将文件从复制<name>.dll<name>.pyd,则如果原始文件实际上不是dll,则会出现此错误。就我而言,构建共享库已关闭,因此基础文件实际上是一个*.lib

我通过将pyd文件加载到DependencyWalker中并发现它无效而发现了此错误。

If your build-system (CMake in my case) copies the file from <name>.dll to <name>.pyd, you will get this error if the original file wasn’t actually a dll. In my case, building shared libraries got switched off, so the underlying file was actually a *.lib.

I discovered this error by loading the pyd file in DependencyWalker and finding that it wasn’t valid.


回答 6

我有同样的问题。这是我所做的:

  1. 我从这里下载pywin32 Wheel文件,然后

  2. 我卸载了pywin32模块。要卸载,请在命令提示符中执行以下命令。

    pip uninstall pywin32

  3. 然后,我重新安装了pywin32。要安装它,请在pywin32 wheel文件所在的目录中打开命令提示符。然后执行以下命令。

    pip install <Name of the wheel file with extension> 车轮文件将类似于:piwin32-XXX-cpXX-none-win32.whl

它为我解决了问题。您可能还想尝试一下。希望它也对您有用。

I had the same problem. Here’s what I did:

  1. I downloaded pywin32 Wheel file from here, then

  2. I uninstalled the pywin32 module. To uninstall execute the following command in Command Prompt.

    pip uninstall pywin32

  3. Then, I reinstalled pywin32. To install it, open the Command Prompt in the same directory where the pywin32 wheel file lies. Then execute the following command.

    pip install <Name of the wheel file with extension> Wheel file will be like: piwin32-XXX-cpXX-none-win32.whl

It solvs the problem for me. You may also like to give it a try. Hope it work for you as well.


回答 7

cv2.pyd/opencv/build/python/2.7/x86文件夹而不是从/x64文件夹复制文件到C:/Python27/Lib/site-packeges。我按照此处提供的其余说明进行操作。

由其他人添加,未经验证:我还复制了文件 cv2.pyd到folder C:/Python27/Lib/site-packages/cv2。有用。

I copied cv2.pyd file from /opencv/build/python/2.7/x86 folder instead of from /x64 folder to C:/Python27/Lib/site-packeges. I followed rest of the instructions provided here.

Added by someone else, not verified: I also copy file cv2.pyd to folder C:/Python27/Lib/site-packages/cv2. It works.


回答 8

对我来说,问题是我在同一个 Eclipse项目中使用了不同版本的Python 。我的设置与“ 项目属性”和“ 运行配置” Python版本不一致。

项目>属性> PyDev中,将解释器设置为Python2.7.11。

“运行配置”>“解释器”中,我正在使用“默认解释器”。将其更改为Python 2.7.11可解决此问题。

For me the problem was that I was using different versions of Python in the same Eclipse project. My setup was not consistent with the Project Properties and the Run Configuration Python versions.

In Project > Properties > PyDev, I had the Interpreter set to Python2.7.11.

In Run Configurations > Interpreter, I was using the Default Interpreter. Changing it to Python 2.7.11 fixed the problem.


回答 9

当我使用32位Windows Installer在系统上卸载并重新安装其他版本的2.7.x Python时,遇到了相同的问题。我的大多数导入语句都出现相同的错误。我卸载了新安装的Python,然后下载了64位Windows安装程序,然后再次重新安装了Python,它可以正常工作。希望对您有帮助。

I faced the same issue when I uninstalled and reinstalled a different version of 2.7.x of Python on my system using a 32 bit Windows Installer. I got the same error on most of my import statements. I uninstalled the newly installed Python and downloaded a 64 bit Windows installer and reinstalled Python again and it worked. Hope this helps you.


回答 10

所以我在Windows下安装vtk时遇到问题(由于我使用python 3.7,到目前为止,仅适用于较旧的python版本,没有可用的二进制文件pip install vtk无法正常工作)

我确实在cmd中编写了python:

Python 3.7.3 on win32

所以我现在知道我的python 3.7.3在32位上运行。

然后,我在下载了正确的车轮 VTK-8.2.0-cp37-cp37m-win32.whl

接下来,我安装了该轮子:

pip install VTK-8.2.0-cp37-cp37m-win32.whl

然后,我对其进行了测试并成功运行:

python
import vtk

So I had problems installing vtk under windows (as I use python 3.7 there is no binary available so far just for older python versions pip install vtk is not working)

I did wrote python in my cmd:

Python 3.7.3 on win32

So I now know I have python 3.7.3 runing on a 32 bit.

I then downloaded the correct wheel at VTK‑8.2.0‑cp37‑cp37m‑win32.whl

Next I instlled that wheel:

pip install VTK-8.2.0-cp37-cp37m-win32.whl

Then I tested it and it worked:

python
import vtk

回答 11

更新numpy。

pip install numpy --upgrade

为我工作!

Update numpy.

pip install numpy --upgrade

Work for me!!


回答 12

首先,我cv2.pyd从复制/opencv/build/python/2.7/x86C:/Python27/Lib/site-packeges。错误是

“ RuntimeError:模块是根据API版本9编译的,但此版本的numpy是7”

然后我安装了numpy-1.8.0-win32-superpack-python2.7.exeopencv,并且工作正常。

>>> import cv2
>>> print cv2.__version__
2.4.13

First I copied cv2.pyd from /opencv/build/python/2.7/x86 to C:/Python27/Lib/site-packeges. The error was

“RuntimeError: module compiled against API version 9 but this version of numpy is 7”

Then I installed numpy-1.8.0-win32-superpack-python2.7.exe and opencv works fine.

>>> import cv2
>>> print cv2.__version__
2.4.13

回答 13

您可以opencv官方非官方站点进行安装。

如果使用,请参考问题和问题Anaconda

You can install opencv from official or unofficial sites.

Refer to this question and this issue if you are using Anaconda.


回答 14

  1. 请确保您已安装python 2.7.12或更低版本,否则您肯定会收到此错误。
  2. 如果操作系统为64位,请确保已安装64位Oracle客户端。
  3. 确保用于Python 2.7的Microsoft Visual C ++编译器对于64位Os为64位,对于32位为32位。注意:-如果您的操作系统是64位,则安装所有64位软件包;如果操作系统是32位,则安装32位软件包。
  1. Please make sure that you have installed python 2.7.12 or below version otherwise you will get this error definitely.
  2. Make sure Oracle client is 64 bit installed if OS is 64 Bit.
  3. Make sure Microsoft Visual C++ Compiler for Python 2.7 is 64 for bit for 64 bit Os or 32 bit for 32 bit. Note:- IF ur OS is 64 bit install all package of 64 bit or if Os is 32 bit install 32 bit package.

回答 15

它有一个非常简单的解决方案。安装后的opencv 地方

cv2.pydC:\opencv\build\python\2.7\ **x64**C:\Python27\Lib\site-packages

代替,cv2.pydC:\opencv\build\python\2.7\ **x86**C:\Python27\Lib\site-packages

It has a very simple solution. After installing opencv place

cv2.pyd from C:\opencv\build\python\2.7\ **x64** to C:\Python27\Lib\site-packages

instead of, place cv2.pyd from C:\opencv\build\python\2.7\ **x86** to C:\Python27\Lib\site-packages


回答 16

尝试导入MySQLdb时出现此错误。

对我有用的是卸载Python,然后重新安装。

安装npm(https://www.npmjs.com/get-npm)后出现错误。它所做的一件事是即使我已经安装了Python,也要安装它。

I got this error when trying to import MySQLdb.

What worked for me was to uninstall Python and then reinstall it.

I got the error after installing npm (https://www.npmjs.com/get-npm). One thing it did was install Python even though I already had it.


回答 17

这对我有用。我尝试了不同的方法,但这是我最好的解决方案。

打开命令提示符并键入以下内容; pip install opencv-python。(确保您的互联网已打开)。之后,请尝试再次导入。

This has worked for me. I have tried different methods but this was my best solution.

Open command prompt and type the following; pip install opencv-python. (make sure your internet is on). after that try importing it again.


回答 18

这个跟我一起工作

pip install -- pywin32==227

This one worked with me

pip install -- pywin32==227

回答 19

我找到了解决方案,也许您可​​以尝试使用cmd窗口而不是anaconda提示窗口来开始您的第一笔测试。

I found the solution, maybe you can try to use the cmd window rather than the anaconda prompt window to start you first scrapy test.


Python的sys.path是从哪里初始化的?

问题:Python的sys.path是从哪里初始化的?

Python的sys.path是从哪里初始化的?

UPD:Python在引用PYTHONPATH之前添加了一些路径:

    >>> import sys
    >>> from pprint import pprint as p
    >>> p(sys.path)
    ['',
     'C:\\Python25\\lib\\site-packages\\setuptools-0.6c9-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\orbited-0.7.8-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\morbid-0.8.6.1-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\demjson-1.4-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\stomper-0.2.2-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\uuid-1.30-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\stompservice-0.1.0-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\cherrypy-3.0.1-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\pyorbited-0.2.2-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\flup-1.0.1-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\wsgilog-0.1-py2.5.egg',
     'c:\\testdir',
     'C:\\Windows\\system32\\python25.zip',
     'C:\\Python25\\DLLs',
     'C:\\Python25\\lib',
     'C:\\Python25\\lib\\plat-win',
     'C:\\Python25\\lib\\lib-tk',
     'C:\\Python25',
     'C:\\Python25\\lib\\site-packages',
     'C:\\Python25\\lib\\site-packages\\PIL',
     'C:\\Python25\\lib\\site-packages\\win32',
     'C:\\Python25\\lib\\site-packages\\win32\\lib',
     'C:\\Python25\\lib\\site-packages\\Pythonwin']

我的PYTHONPATH是:

    PYTHONPATH=c:\testdir

我想知道PYTHONPATH之前的那些路径来自哪里?

Where is Python’s sys.path initialized from?

UPD: Python is adding some paths before refering to PYTHONPATH:

    >>> import sys
    >>> from pprint import pprint as p
    >>> p(sys.path)
    ['',
     'C:\\Python25\\lib\\site-packages\\setuptools-0.6c9-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\orbited-0.7.8-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\morbid-0.8.6.1-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\demjson-1.4-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\stomper-0.2.2-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\uuid-1.30-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\stompservice-0.1.0-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\cherrypy-3.0.1-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\pyorbited-0.2.2-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\flup-1.0.1-py2.5.egg',
     'C:\\Python25\\lib\\site-packages\\wsgilog-0.1-py2.5.egg',
     'c:\\testdir',
     'C:\\Windows\\system32\\python25.zip',
     'C:\\Python25\\DLLs',
     'C:\\Python25\\lib',
     'C:\\Python25\\lib\\plat-win',
     'C:\\Python25\\lib\\lib-tk',
     'C:\\Python25',
     'C:\\Python25\\lib\\site-packages',
     'C:\\Python25\\lib\\site-packages\\PIL',
     'C:\\Python25\\lib\\site-packages\\win32',
     'C:\\Python25\\lib\\site-packages\\win32\\lib',
     'C:\\Python25\\lib\\site-packages\\Pythonwin']

My PYTHONPATH is:

    PYTHONPATH=c:\testdir

I wonder where those paths before PYTHONPATH’s ones come from?


回答 0

“从环境变量PYTHONPATH初始化,加上与安装有关的默认值”

http://docs.python.org/library/sys.html#sys.path

“Initialized from the environment variable PYTHONPATH, plus an installation-dependent default”

http://docs.python.org/library/sys.html#sys.path


回答 1

Python确实努力进行智能设置sys.path。如何设置可能会变得非常 复杂。下面的指南是一个打了折扣的,有点不完全,有些-错,但希望-有用的时候Python会什么的使用会发生什么的职级和文件Python程序员指南初始值sys.pathsys.executablesys.exec_prefix,和sys.prefix正常的 python安装上。

首先,python会尽最大努力根据操作系统告诉它在文件系统上的实际物理位置。如果操作系统只是说“ python”正在运行,它将在$ PATH中找到自己。它解析任何符号链接。完成此操作后,它将找到的可执行文件的路径用作sys.executable,no ifs,ands或buts的值。

接下来,确定用于初始值sys.exec_prefixsys.prefix

如果pyvenv.cfg在与该目录相同的目录中有一个文件, sys.executable或者在一个目录中,则python会查看该文件。不同的操作系统对此文件执行不同的操作。

python在此配置文件中查找的值之一是configuration选项home = <DIRECTORY>sys.executable 当它动态设置以后的初始值时,Python将使用此目录而不是包含的目录sys.prefix。如果该applocal = true设置出现在pyvenv.cfgWindows 的 文件中,但没有出现在home = <DIRECTORY>设置中,sys.prefix则将被设置为包含的目录sys.executable

接下来,PYTHONHOME检查环境变量。在Linux和Mac上, sys.prefixsys.exec_prefix设置为PYTHONHOME环境变量,如果它存在,并取代任何home = <DIRECTORY>的设置pyvenv.cfg。在Windows上, sys.prefix并且sys.exec_prefix设置为PYTHONHOME环境变量(如果存在),除非在中存在home = <DIRECTORY>设置,否则将使用该设置pyvenv.cfg

否则,可以通过从或指定的目录(如果有)的位置向后走来找到sys.prefix和。sys.exec_prefixsys.executablehomepyvenv.cfg

如果lib/python<version>/dyn-load在该目录或其任何父目录中找到该文件,则将该目录设置为 sys.exec_prefix在Linux或Mac上。如果lib/python<version>/os.py在目录或其任何子目录中找到该文件 ,则将该目录设置为sys.prefix在Linux,Mac和Windows上,并sys.exec_prefix设置为与Windows 相同的值 sys.prefix。如果applocal = true已设置,则在Windows上将跳过整个步骤 。使用的目录,sys.executable或者如果home设置了目录,则将其pyvenv.cfg用于的初始值sys.prefix

如果找不到或没有找到这些“地标”文件sys.prefix,则python设置sys.prefix为“后备”值。Linux和Mac,例如,使用预编译的缺省值的数值sys.prefixsys.exec_prefix。Windows等到sys.path完全确定要为设置后备值 为止sys.prefix

然后,(您一直在等待)python确定要包含在中的初始值sys.path

  1. python正在执行的脚本目录被添加到sys.path。在Windows上,这始终是空字符串,它告诉python使用脚本所在的完整路径。
  2. 除非您在Windows上并且在中设置为true sys.path否则将添加PYTHONPATH环境变量的内容(如果applocal已设置)pyvenv.cfg
  3. <prefix>/lib/python35.zipLinux / Mac和os.path.join(os.dirname(sys.executable), "python.zip")Windows 上 的zip文件路径已添加到中sys.path
  4. 如果在Windows上没有applocal = true在中设置No pyvenv.cfg,则HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\添加注册表项的子项的内容( 如果有)。
  5. 如果在Windows上未applocal = true在中设置No pyvenv.cfg,并且sys.prefix找不到,则添加注册表项的核心内容HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\如果存在);
  6. 如果在Windows上没有applocal = true在中设置No pyvenv.cfg,则HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\添加注册表项的子项的内容( 如果有)。
  7. 如果在Windows上未applocal = true在中设置No pyvenv.cfg,并且sys.prefix找不到,则添加注册表项的核心内容HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\如果存在);
  8. 如果在Windows上并且未设置PYTHONPATH,则找不到前缀,并且不存在注册表项,则添加PYTHONPATH的相对编译时值;否则,将忽略此步骤。
  9. 相对于dynamic-found添加了编译时宏PYTHONPATH中的路径sys.prefix
  10. 在Mac和Linux上,将sys.exec_prefix添加的值。在Windows上,添加了用于(或将要使用)动态搜索的目录sys.prefix

在Windows的现阶段,如果未找到前缀,则python将尝试通过搜索所有目录中sys.path的地标文件来确定它,就像它尝试使用sys.executable以前的目录一样,直到找到了东西。如果不是,sys.prefix则留空。

最后,在完成所有这些之后,Python加载了site模块,这进一步为sys.path以下模块添加了一些内容:

它从头和尾部分开始最多构建四个目录。头部使用sys.prefixsys.exec_prefix; 空头被跳过。对于尾部,它使用空字符串,然后lib/site-packages(在Windows上)或lib/pythonX.Y/site-packages (然后lib/site-python在Unix和Macintosh上)使用。对于每个不同的首尾组合,它会查看它是否指向现有目录,如果是,则将其添加到sys.path中,并检查新添加的配置文件路径。

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says “python” is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can’t find these “landmark” files or sys.prefix hasn’t been found yet, then python sets sys.prefix to a “fallback” value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you’ve all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you’re on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn’t, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.


将Python搜索路径扩展到其他来源

问题:将Python搜索路径扩展到其他来源

我刚刚加入了一个具有相当大的现有代码库的项目。我们用linux开发,不使用和IDE。我们通过命令行运行。我试图弄清楚如何在运行项目模块时让python搜索正确的路径。例如,当我运行类似的内容时:

python someprojectfile.py

我懂了

ImportError: no module named core.'somemodule'

我认为所有导入的内容都是这样,我认为这是路径问题。

TLDR:

如何~/codez/project/在导入语句期间让Python搜索* .py文件以及所有文件和文件夹。

I have just joined a project with a rather large existing code base. We develop in linux and do not use and IDE. We run through the command line. I’m trying to figure out how to get python to search for the right path when I run project modules. For instance, when I run something like:

python someprojectfile.py

I get

ImportError: no module named core.'somemodule'

I get this for all of my imports to I assume it’s an issue with the path.

TLDR:

How do I get Python to search ~/codez/project/ and all the files and folders for *.py files during import statements.


回答 0

有几种方法可以做到这一点:

  • 将环境变量设置PYTHONPATH为用冒号分隔的目录列表,以搜索导入的模块。
  • 在您的程序中,用于sys.path.append('/path/to/search')添加您希望Python搜索导入的模块的目录名称。sys.path只是Python在每次被要求导入模块时搜索的目录列表,您可以根据需要进行更改(尽管我不建议删除任何标准目录!)。Python启动时,您放入环境变量中的所有目录PYTHONPATH都将插入sys.path其中。
  • 用于site.addsitedir向添加目录sys.path。此和纯附加的区别在于,当您使用时addsitedir,它还会.pth在该目录中查找文件,并使用它们sys.path根据文件的内容向其中添加其他目录。有关更多详细信息,请参见文档。

您要使用哪一种取决于您的情况。请记住,当您将项目分发给其他用户时,他们通常会以某种方式安装该项目,以便Python的导入程序会自动检测到Python代码文件(即,程序包通常安装在site-packages目录中),因此,如果您弄乱了sys.path代码,当该代码在另一台计算机上运行时,可能是不必要的,甚至可能产生不利影响。对于开发而言,我会大胆猜测设置PYTHONPATH通常是最好的选择。

但是,当您使用仅在自己的计算机上运行的内容时(或当您进行非标准设置时(例如有时在Web应用程序框架中)),执行诸如此类的操作并非完全不常见。

import sys
from os.path import dirname
sys.path.append(dirname(__file__))

There are a few possible ways to do this:

  • Set the environment variable PYTHONPATH to a colon-separated list of directories to search for imported modules.
  • In your program, use sys.path.append('/path/to/search') to add the names of directories you want Python to search for imported modules. sys.path is just the list of directories Python searches every time it gets asked to import a module, and you can alter it as needed (although I wouldn’t recommend removing any of the standard directories!). Any directories you put in the environment variable PYTHONPATH will be inserted into sys.path when Python starts up.
  • Use site.addsitedir to add a directory to sys.path. The difference between this and just plain appending is that when you use addsitedir, it also looks for .pth files within that directory and uses them to possibly add additional directories to sys.path based on the contents of the files. See the documentation for more detail.

Which one of these you want to use depends on your situation. Remember that when you distribute your project to other users, they typically install it in such a manner that the Python code files will be automatically detected by Python’s importer (i.e. packages are usually installed in the site-packages directory), so if you mess with sys.path in your code, that may be unnecessary and might even have adverse effects when that code runs on another computer. For development, I would venture a guess that setting PYTHONPATH is usually the best way to go.

However, when you’re using something that just runs on your own computer (or when you have nonstandard setups, e.g. sometimes in web app frameworks), it’s not entirely uncommon to do something like

import sys
from os.path import dirname
sys.path.append(dirname(__file__))

回答 1

您还应该在这里阅读有关python软件包的信息:http : //docs.python.org/tutorial/modules.html

从您的示例中,我想您确实在拥有一个软件包~/codez/project__init__.pypython目录中的文件将目录映射到命名空间。如果所有子目录都有一个__init__.py文件,则只需将基本目录添加到中PYTHONPATH。例如:

PYTHONPATH = $ PYTHONPATH:$ HOME / adaifotis / project

正如David解释的那样,除了测试您的PYTHONPATH环境变量外,您还可以像这样在python中对其进行测试:

$ python
>>> import project                      # should work if PYTHONPATH set
>>> import sys
>>> for line in sys.path: print line    # print current python path

You should also read about python packages here: http://docs.python.org/tutorial/modules.html.

From your example, I would guess that you really have a package at ~/codez/project. The file __init__.py in a python directory maps a directory into a namespace. If your subdirectories all have an __init__.py file, then you only need to add the base directory to your PYTHONPATH. For example:

PYTHONPATH=$PYTHONPATH:$HOME/adaifotis/project

In addition to testing your PYTHONPATH environment variable, as David explains, you can test it in python like this:

$ python
>>> import project                      # should work if PYTHONPATH set
>>> import sys
>>> for line in sys.path: print line    # print current python path


回答 2

我知道这个线程有些陈旧,但是花了我一些时间才能真正理解这一点,所以我想分享一下。

在我的项目中,我的主脚本位于父目录中,为了区分模块,我将所有支持的模块放在一个称为“模块”的子文件夹中。在我的主脚本中,我像这样导入这些模块(对于名为report.py的模块):

from modules.report import report, reportError

如果我调用主脚本,则可以正常工作。但是,我想通过main()在每个模块中包含一个并直接调用每个模块来测试每个模块,如下所示:

python modules/report.py

现在,Python抱怨它找不到“称为模块的模块”。这里的关键是,默认情况下,Python在其搜索路径中包括脚本的文件夹,但不是CWD。因此,此错误实际上表示“我找不到模块子文件夹”。这是因为report.py模块所在的目录中没有“ modules”子目录。

我发现最巧妙的解决方案是通过在顶部包括以下内容来将CWD附加到Python搜索路径中:

import sys

sys.path.append(".")

现在,Python搜索CWD(当前目录),找到“模块”子文件夹,一切顺利。

I know this thread is a bit old, but it took me some time to get to the heart of this, so I wanted to share.

In my project, I had the main script in a parent directory, and, to differentiate the modules, I put all the supporting modules in a sub-folder called “modules”. In my main script, I import these modules like this (for a module called report.py):

from modules.report import report, reportError

If I call my main script, this works. HOWEVER, I wanted to test each module by including a main() in each, and calling each directly, as:

python modules/report.py

Now Python complains that it can’t find “a module called modules”. The key here is that, by default, Python includes the folder of the script in its search path, BUT NOT THE CWD. So what this error says, really, is “I can’t find a modules subfolder”. The is because there is no “modules” subdirectory from the directory where the report.py module resides.

I find that the neatest solution to this is to append the CWD in Python search path by including this at the top:

import sys

sys.path.append(".")

Now Python searches the CWD (current directory), finds the “modules” sub-folder, and all is well.


回答 3

我阅读了此问题以寻找答案,但不喜欢其中任何一个。

所以我写了一个快速而肮脏的解决方案。只需将其放在sys.path上的某个位置,它将在folder(来自当前工作目录)或下添加任何目录abspath

#using.py

import sys, os.path

def all_from(folder='', abspath=None):
    """add all dirs under `folder` to sys.path if any .py files are found.
    Use an abspath if you'd rather do it that way.

    Uses the current working directory as the location of using.py. 
    Keep in mind that os.walk goes *all the way* down the directory tree.
    With that, try not to use this on something too close to '/'

    """
    add = set(sys.path)
    if abspath is None:
        cwd = os.path.abspath(os.path.curdir)
        abspath = os.path.join(cwd, folder)
    for root, dirs, files in os.walk(abspath):
        for f in files:
            if f[-3:] in '.py':
                add.add(root)
                break
    for i in add: sys.path.append(i)

>>> import using, sys, pprint
>>> using.all_from('py') #if in ~, /home/user/py/
>>> pprint.pprint(sys.path)
[
#that was easy
]

我之所以喜欢它,是因为我可以为一些随机工具提供一个文件夹,而不必让它们成为软件包或任何东西的一部分,并且仍然可以通过几行代码访问其中的一些(或全部)。

I read this question looking for an answer, and didn’t like any of them.

So I wrote a quick and dirty solution. Just put this somewhere on your sys.path, and it’ll add any directory under folder (from the current working directory), or under abspath:

#using.py

import sys, os.path

def all_from(folder='', abspath=None):
    """add all dirs under `folder` to sys.path if any .py files are found.
    Use an abspath if you'd rather do it that way.

    Uses the current working directory as the location of using.py. 
    Keep in mind that os.walk goes *all the way* down the directory tree.
    With that, try not to use this on something too close to '/'

    """
    add = set(sys.path)
    if abspath is None:
        cwd = os.path.abspath(os.path.curdir)
        abspath = os.path.join(cwd, folder)
    for root, dirs, files in os.walk(abspath):
        for f in files:
            if f[-3:] in '.py':
                add.add(root)
                break
    for i in add: sys.path.append(i)

>>> import using, sys, pprint
>>> using.all_from('py') #if in ~, /home/user/py/
>>> pprint.pprint(sys.path)
[
#that was easy
]

And I like it because I can have a folder for some random tools and not have them be a part of packages or anything, and still get access to some (or all) of them in a couple lines of code.


回答 4

我发现最简单的方法是创建一个文件“ any_name.pth”,并将其放在文件夹“ \ Lib \ site-packages”中。您应该在安装python的任何位置都找到该文件夹​​。

在该文件中,放入要保留要导入模块的目录列表。例如,在该文件中这样一行:

C:\ Users \ example … \ example

您可以通过在python中运行它来告诉它工作:

import sys
for line in sys: print line

您将看到已打印的目录,以及从中可以导入的目录。现在,您可以轻松地导入该目录中的“ mymodule.py”文件:

import mymodule

这将不会导入子文件夹。为此,您可以想象创建一个python脚本来创建一个.pth文件,其中包含您定义的文件夹的所有子文件夹。让它在启动时运行。

The easiest way I find is to create a file “any_name.pth” and put it in your folder “\Lib\site-packages”. You should find that folder wherever python is installed.

In that file, put a list of directories where you want to keep modules for importing. For instance, make a line in that file like this:

C:\Users\example…\example

You will be able to tell it works by running this in python:

import sys
for line in sys: print line

You will see your directory printed out, amongst others from where you can also import. Now you can import a “mymodule.py” file that sits in that directory as easily as:

import mymodule

This will not import subfolders. For that you could imagine creating a python script to create a .pth file containing all sub folders of a folder you define. Have it run at startup perhaps.


回答 5

旧问题的新选择。在Debian上
安装fail2ban软件包,看起来像是硬编码安装/usr/lib/python3/dist-packages/fail2ban在python3以外的路径上sys.path


> python3
Python 3.7.3 (v3.7.3:ef4ec6ed12, Jun 25 2019, 18:51:50)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/lib/python3.7/site-packages']
>>>

因此,我(bash)将库链接到较新的版本,而不仅仅是复制。
将来对原始应用程序的更新也将自动应用于链接版本。

 if [ -d /usr/lib/python3/dist-packages/fail2ban ]
   then
      for d in /usr/lib/python3.*
      do
         [ -d ${d}/fail2ban ] || \
            ln -vs /usr/lib/python3/dist-packages/fail2ban ${d}/
      done
   fi

New option for old question.
Installing fail2ban package on Debian, looks like it’s hardcoded to install on /usr/lib/python3/dist-packages/fail2ban a path not on python3 sys.path.


> python3
Python 3.7.3 (v3.7.3:ef4ec6ed12, Jun 25 2019, 18:51:50)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/lib/python3.7/site-packages']
>>>

so, instead of just copying, I (bash) linked the library to newer versions.
Future updates to the original app, will also be automatically applied to the linked versions.

 if [ -d /usr/lib/python3/dist-packages/fail2ban ]
   then
      for d in /usr/lib/python3.*
      do
         [ -d ${d}/fail2ban ] || \
            ln -vs /usr/lib/python3/dist-packages/fail2ban ${d}/
      done
   fi

Windows在subprocess.call()上找不到文件

问题:Windows在subprocess.call()上找不到文件

我收到以下错误:

WindowsError: [Error 2] The system cannot find the file specified

我的代码是:

subprocess.call(["<<executable file found in PATH>>"])

Windows 7,64位。Python 3.x最新,稳定。

有任何想法吗?

谢谢,

I am getting the following error:

WindowsError: [Error 2] The system cannot find the file specified

My code is:

subprocess.call(["<<executable file found in PATH>>"])

Windows 7, 64 bit. Python 3.x latest, stable.

Any ideas?

Thanks,


回答 0

当命令是内置的shell时,请在调用中添加“ shell = True”。

例如,dir您将输入:

import subprocess
subprocess.call('dir', shell=True)

引用文档:

在Windows上唯一需要指定shell = True的时间是将要执行的命令内置到shell中(例如dir或copy)。您不需要shell = True即可运行批处理文件或基于控制台的可执行文件。

When the command is a shell built-in, add a ‘shell=True’ to the call.

E.g. for dir you would type:

import subprocess
subprocess.call('dir', shell=True)

To quote from the documentation:

The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable.


回答 1

在Windows上,我相信除非您通过subprocessPATH否则shell=True模块不会进入,因为它CreateProcess()在后台使用。但是,shell=True如果传递的参数可能来自程序外部,则可能存在安全风险。为了subprocess仍然能找到正确的可执行文件,你可以使用shutil.which。假设您中的可执行文件PATH名为frob

subprocess.call([shutil.which('frob'), arg1, arg2])

(这适用于Python 3.3及更高版本。)

On Windows, I believe the subprocess module doesn’t look in the PATH unless you pass shell=True because it use CreateProcess() behind the scenes. However, shell=True can be a security risk if you’re passing arguments that may come from outside your program. To make subprocess nonetheless able to find the correct executable, you can use shutil.which. Suppose the executable in your PATH is named frob:

subprocess.call([shutil.which('frob'), arg1, arg2])

(This works on Python 3.3 and above.)


回答 2

在Windows上,您必须通过cmd.exe进行调用。如Apalala所述,Windows命令不是作为单独的可执行文件在cmd.exe中实现的。

例如

subprocess.call(['cmd', '/c', 'dir'])

/ c告诉cmd运行以下命令

这比使用shell = True(允许shell注入)更安全。

On Windows you have to call through cmd.exe. As Apalala mentioned, Windows commands are implemented in cmd.exe not as separate executables.

e.g.

subprocess.call(['cmd', '/c', 'dir'])

/c tells cmd to run the follow command

This is safer than using shell=True, which allows shell injections.


回答 3

如果您使用的是Powershell,则将在其中subprocess.call(['powershell','-command','dir'])。Powershell支持大部分POSIX命令

If you are using powershell, then in it will be subprocess.call(['powershell','-command','dir']). Powershell supports a large portion of POSIX commands


回答 4

经过大量的抓挠之后,我发现在64位计算机上运行32位版本的python时,运行位于C:\ Windows \ System32 \中的文件是一个潜在的问题,这是由于Windows试图使该过程变得更智能,以及将对C:\ Windows \ System32的调用重定向到C:\ Windows \ SysWOW64。

我在这里找到了如何解决此问题的示例:http : //code.activestate.com/recipes/578035-disable-file-system-redirector/

After much head scratching, I discovered that running a file that is located in C:\Windows\System32\ while running a 32bit version of python on a 64bit machine is a potential issue, due to Windows trying to out-smart the process, and redirect calls to C:\Windows\System32 to C:\Windows\SysWOW64.

I found an example of how to fix this here: http://code.activestate.com/recipes/578035-disable-file-system-redirector/


回答 5

引用文档:

“在Python 3.5之前,这三个函数包含用于子过程的高级API。您现在可以在许多情况下使用run(),但是许多现有代码都调用了这些函数。”

因此:对于Python 3.5及更高版本,请使用subprocess.run而不是subprocess.call

To quote from the documentation:

“Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use run() in many cases, but lots of existing code calls these functions.”

SO: instead of subprocess.call use subprocess.run for Python 3.5 and above


回答 6

在调用PHP时遇到了相同的问题。原因是PHP不在PATH中,所以找不到命令PHP。但是PowerShell发现它确实存在于当前位置,如果我信任此命令,建议将“ PHP”替换为“。\ PHP”。然后运行良好。

I met the same issue while I was calling a PHP. The reason is PHP isn’t in PATH so the command PHP was not found. But PowerShell found it does exist in the current location and it suggests replacing the ‘PHP’ by the ‘.\PHP’ if I trust this command. Then it runs well.