1

完成后,$ pip install path/to/MyProject-0.1.0.tar.gz我可以import myproject使用 python 解释器从我计算机上的每个目录中成功完成。

但是,我的目标是能够$ myproject从每个目录运行。当我跑步时,$ myproject我得到了这个:

IOError: [Errno 2] No such file or directory: '/home/username/.virtualenvs/vir_env/local/lib/python2.7/site-packages/myproject/myproject_style.cssc'

我查看了/home/username/.virtualenvs/vir_env/local/lib/python2.7/site-packages/myproject/目录,myproject_style.css文件在那里。

注意错误说cssc而不是css. 我不知道为什么会出现此错误,因为当我导航到 myproject 目录并执行时程序运行得非常好$ python __init__.py

项目概况:

.
├── MyProject.egg-info
│   ├── dependency_links.txt
│   ├── entry_points.txt
│   ├── PKG-INFO
│   ├── requires.txt
│   ├── SOURCES.txt
│   └── top_level.txt
├── dist
│   └── MyProject-0.1.0.tar.gz
├── LICENSE.txt
├── MANIFEST.in
├── myproject
│   ├── __init__.py
│   └── myproject_style.css
├── README
└── setup.py

安装程序.py

from setuptools import setup

setup(
    name='MyProject',
    version='0.1.0',
    author='B',
    author_email='jrh@example.com',
    packages=['myproject', ],
    include_package_data=True,
    url='http://pypi.python.org/pypi/MyProject/',
    license='LICENSE.txt',
    package_data={'': ['myproject_style.css']},
    data_files=[('myproject',['myproject_style.css'])],
    entry_points={
    'console_scripts': ['myproject = myproject:main', ],},
    description='Shitz and giggles.',
    long_description=open('README').read(),
)

清单文件

include myproject/myproject_style.css

初始化.py

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

import sys
try:
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import HtmlFormatter
except:
    print "\npygments is not installed yet. Install pygments or run 'pip install -r requirements.txt'.\n"
    sys.exit()

import argparse

import SimpleHTTPServer
import BaseHTTPServer
import webbrowser
import SocketServer
import os
import distutils.sysconfig as dc

import urllib
import cgi
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

class MyProjectHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        path = os.path.join(os.getcwdu(), self.path[1:])
        if os.path.exists(path) and path.endswith('.py'):
            with open(path) as file:
                cod = file.read()
                hl = highlight(cod, PythonLexer(), HtmlFormatter(noclasses=True, linenos='table', style='friendly')
                hl = '<body style="background:#f0f0f0">'+hl+'</body>'
                print hl
                self.send_response(200)
                self.end_headers()
                self.wfile.write(hl)
        else:
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

    def list_directory(self, path):
        try:
            lis = os.listdir(path)
        except os.error:
            self.send_error(404, "No permission to list directory")
            return None
        lis.sort(key=lambda a: a.lower())
        f = StringIO()
        css_file = open(path_to_myproject_css).read()
        f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
        f.write("<html>\n<head>\n<title>Directory and python file listing for %s</title>\n" % path)
        f.write('<style type="text/css"> %s</style>\n' %css_file)
        f.write('</head>\n')
        f.write("<body>\n<div class=page-container>\n<h2>Myproject</h2>\n")
        f.write("<ul class=shortcut-list>\n")
        f.write("<li class=shortcut-list><a href=%s>Python standard library modules</a></li>" % path_standard_library)
        f.write("\n<li class=shortcut-list><a href=%s>User installed python modules</a></li>" % path_external_packages)
        try:
            with open(os.getenv("HOME")+'/.myprojectrc', "r") as prc: 
                prc_string = prc.read()
            f.write(prc_string)
        except:
            pass

        f.write("\n</ul>")  
        f.write("\n<h5>Directory and python file listing for %s</h5>" % path)
        f.write("\n<hr>\n<ul>\n")
        os.chdir("/")
        for name in lis:
            fullname = os.path.join(path, name) 
            displayname = name
            condition1 = name.endswith(u'.py') or os.path.isdir(fullname) or os.path.islink(fullname) 
            condition2 = name.endswith(u'.egg-info') or name.endswith(u'.egg')
            if condition1 and not condition2:    
                if os.path.isdir(fullname):
                    displayname = name + "/"
                if os.path.islink(fullname):
                    displayname = name + "@"
                f.write('<li><a href="%s">%s</a>\n'% (fullname, displayname))
        f.write("</ul>\n<hr>\n</div>\n</body>\n</html>\n")
        length = f.tell()
        f.seek(0)
        self.send_response(200)
        encoding = sys.getfilesystemencoding()
        self.send_header("Content-type", "text/html; charset=%s" % encoding)
        self.send_header("Content-Length", str(length))
        self.end_headers()
        return f  

def _add_argument_handler():
    if os.path.isdir(subcmd):
        print "\nYou added '%s' to the top directory links." % subcmd
        d_name = raw_input("\nSpecify the name of this link. Just pressing <enter> uses '%s' as the link name.\n> " % subcmd)
        print ""
        if len(d_name) == 0:
            d_name = subcmd
        else:
            pass
        with open(os.getenv("HOME")+'/.myprojectrc', "a") as prc:
            prc.write("<li class=shortcut-list><a href=%s>%s</a></li>\n" % (subcmd, d_name))
    else:
        print "\n'%s' is not an existing directory path.\n" % subcmd

def _remove_argument_handler():
    if not _link_name_checker(subcmd):
        print "\nthe top directory link name '%s' does not exist yet.\n" % subcmd
    else:
        _remove_line(subcmd)
        print "\nYou removed the top directory link name '%s'.\n" % subcmd

def _link_name_checker(subcmd):
    with open(os.getenv("HOME")+'/.myprojectrc', "r") as prc:
        lines = prc.readlines()
        for line in lines:
            suff = "%s</a></li>\n" % subcmd
            if line.endswith(suff):
                return True
            else:
                pass
        return False

def _remove_line(del_d_name):
    with open(os.getenv("HOME")+'/.myproject', "r") as prc:
        lines = prc.readlines()

    with open(os.getenv("HOME")+'/.myproject', "w") as prc:
        for line in lines:
            suff = "%s</a></li>\n" % del_d_name
            if not line.endswith(suff):
                prc.write(line)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("cmd", help="Execute a command", action="store", nargs='*')
    args = parser.parse_args()

    if args.cmd:
        cmd, subcmd = args.cmd
        if cmd == "add":
            _add_argument_handler()
        if cmd == "remove":
            _remove_argument_handler()
        else:
            print "\n'%s' is not a valid argument.\n" % cmd
        sys.exit()
    else:
        pass

    webbrowser.open("http://localhost:8090")

    os.chdir("/usr/lib/python2.7")

    print "\nPress <CTRL> + C to stop running myproject.\n"

    server = BaseHTTPServer.HTTPServer(('', 8090), MyProjectHTTPRequestHandler)
    try:
        server.serve_forever()
    except:
        print "\nBye bye!\n"

path_to_myproject = os.path.abspath(__file__)
path_to_myproject_css = path_to_myproject.replace("/__init__.py", "/myproject_style.css")
path_external_packages = dc.get_python_lib()
path_standard_library = dc.get_python_lib(standard_lib=True)

if __name__ == '__main__':
    main()
4

1 回答 1

3

问题并不那么明显,但我想我知道出了什么问题。

这行代码:

path_to_myproject = os.path.abspath(__file__)

不仅可以返回“.../__init__.py”,还可以返回“.../__init__.pyc”字符串

因此这行代码:

path_to_myproject_css = path_to_myproject.replace("/__init__.py", "/myproject_style.css")

不仅会使用 __init__.py,还会使用 __init__。pyc - py 模块的字节编译版本。这是您获得csc而不是css的最可能原因;您只需在字符串“.../__init__.pyc”中将“/__init__.py”替换为“/myproject_style.css”。

于 2012-08-12T07:55:34.510 回答