我有一个看起来像这样的项目:
my_project/
__init__.py -- empty
run.py
datacheck/
__init__.py -- empty
datacheck.py -- containing class DataCheck(object)
config.py -- containing BusinessConfig(object)
business.py -- containing class BusinessCheck(DataCheck)
Run Code Online (Sandbox Code Playgroud)
我PYTHONPATH的配置为/ my_project.
在run.py中,我有以下代码:
from datacheck.business import BusinessCheck
business = BusinessCheck()
business.check_data()
Run Code Online (Sandbox Code Playgroud)
在business.py中,我有以下导入失败:
from datacheck.config import BusinessConfig
from datacheck.datacheck import DataCheck
Run Code Online (Sandbox Code Playgroud)
像from .config import BusinessConfig作品一样的相对导入- 但是我已经在很多线程中读到绝对导入是首选.
为了做一个简单的测试,我还创建了以下内容:
myproject/
__init__.py -- empty
run_test.py
test/
__init__.py -- empty
test1.py -- containing class Test1(object)
test2.py -- containing class Test2(Test1)
Run Code Online (Sandbox Code Playgroud)
run_test.py导入并运行Test2该类,这并没有失败.
它让我有点大吃一惊,我不明白为什么我在datacheck中的绝对导入不起作用 - 谁能解释一下?
我的应用程序是一个专门的文件比较实用程序,显然只比较一个文件nargs='+'是没有意义的,所以不太合适.
nargs=N只排除最多的N参数,但只要至少有两个参数,我需要接受无数个参数.
我导入了两个库urllib和from urllib.request import urlopen.
第二个包含在第一个中
当我查看代码并尝试删除该from urllib.request import urlopen行时,我收到此消息:
opnerHTMLnum = urllib.request.build_opener()
AttributeError: 'module' object has no attribute 'request'
Run Code Online (Sandbox Code Playgroud)
当我恢复from urllib.request import urlopen代码运行时.
有谁能解释为什么?
import re
#import http.cookiejar
import os.path
#import time
#import urllib3
import urllib
from urllib.request import urlopen
import sys
import smtplib
from email.mime.text import MIMEText
# ...
opnerHTMLnum = urllib.request.build_opener()
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用下面的脚本检查check_output的用法并运行编译错误,我在哪里错了?
import os
import subprocess
from subprocess import check_output
#result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])
SCRIPT_ROOT=subprocess.check_output(["pwd","shell=True"])
print SCRIPT_ROOT
def main ():
pass
if __name__ == '__main__':
main()
Traceback (most recent call last):
File "test.py", line 3, in <module>
from subprocess import check_output
ImportError: cannot import name check_output
Run Code Online (Sandbox Code Playgroud) 通常,要添加subparser,argparse您必须执行以下操作:
parser = ArgumentParser()
subparsers = parser.add_subparser()
subparser = subparsers.add_parser()
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我正在尝试使用自己的解析器添加另一个命令行脚本,作为我的主脚本的子命令.是否有捷径可寻?
编辑:澄清一下,我有一个script.py看起来像这样的文件:
def initparser():
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')
return parser
def func(args):
#args is a Namespace, this function does stuff with it
if __name__ == '__main__':
initparser().parse_args()
Run Code Online (Sandbox Code Playgroud)
所以我可以这样运行:
python script.py --foo --bar
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写一个模块app.py,它是一个带有几个子命令的命令行界面,所以我可以运行类似的东西:
python app.py script --foo --bar
Run Code Online (Sandbox Code Playgroud)
我希望能够直接使用我从initparser()创建的解析器作为子解析器,而不是将所有initparser()逻辑复制并粘贴到其中app.py.这可能吗?
我花了一些时间在Python记录器上查看网站问题,希望我能在那里得到解决.我已经设置了一个带有两个流处理程序的记录器,它们具有不同的格式和级别的日志记录,这是我的代码库中的功能代码段:
import os
import time
import logging
LOG_LEVELS = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
TEST_RESULT_LEVELV_NUM = 51
# http://stackoverflow.com/a/11784984/196832
def status(self, message, *args, **kws):
self._log(TEST_RESULT_LEVELV_NUM, message, args, **kws)
logging.addLevelName(TEST_RESULT_LEVELV_NUM, "RESULT")
logging.Logger.result = status
def setup_logging(level=0, quiet=False, logdir=None):
logger = logging.getLogger('juju-test')
ffmt = logging.Formatter('%(asctime)s %(name)s %(levelname)-8s: %(message)s')
cfmt = logging.Formatter('%(name)s %(levelname)s: %(message)s')
#logger.setLevel(0)
if level >= len(LOG_LEVELS):
level = len(LOG_LEVELS) - 1
if logdir:
if not os.path.exists(logdir):
os.makedirs(logdir)
logfile = os.path.join(logdir, 'juju-test.%s.log' % int(time.time()))
fh = logging.FileHandler(logfile)
# Always at least log …Run Code Online (Sandbox Code Playgroud) 我想附加一个包含函数返回值列表的表,其中一些是元组:
def get_foo_bar():
# do stuff
return 'foo', 'bar'
def get_apple():
# do stuff
return 'apple'
table = list()
table.append([get_foo_bar(), get_apple()])
Run Code Online (Sandbox Code Playgroud)
这会产生:
>>> table
[[('foo', 'bar'), 'apple']]
Run Code Online (Sandbox Code Playgroud)
但我需要将返回的元组解压缩到该列表中,如下所示:
[['foo', 'bar', 'apple']]
Run Code Online (Sandbox Code Playgroud)
由于解包函数调用[*get_foo_bar()]不起作用,我分配了两个变量用于接收元组的值并改为添加它们:
foo, bar = get_foo_bar()
table.append([foo, bar, get_apple()])
Run Code Online (Sandbox Code Playgroud)
这有效,但可以避免吗?
我有以下代码:
# -*- coding: utf-8 -*-
print u"William Burges (1827–81) was an English architect and designer."
Run Code Online (Sandbox Code Playgroud)
当我尝试从 cmd 运行它时。我收到以下消息:
Traceback (most recent call last):
File "C:\Python27\utf8.py", line 3, in <module>
print u"William Burges (1827???81) was an English architect and designer."
File "C:\Python27\lib\encodings\cp775.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position
20: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题并使 Python 读取这个 \u2013 字符?以及为什么 Python 不使用现有代码读取它,我认为 utf-8 适用于每个字符。
谢谢
编辑:
此代码打印出想要的结果:
# -*- coding: utf-8 -*-
print …Run Code Online (Sandbox Code Playgroud) 我想安装 yajl-py。我尝试过这个:pip install yajl-py。但有一个错误:
OSError : Yajl shared object cannot be found . Please install Yajl and confirm it is on your shared lib path.
Run Code Online (Sandbox Code Playgroud)
你有什么想法吗?
是否可以使用该requests模块与 FTP 站点交互? requests获取 HTTP 页面非常方便,但是当我尝试使用 FTP 站点时,我似乎收到了 Schema 错误。
有什么我遗漏的东西requests可以让我做 FTP 请求,还是不支持?
python ×10
argparse ×2
python-2.7 ×2
cmd ×1
ftp ×1
importerror ×1
json ×1
logging ×1
pip ×1
python-3.x ×1
subprocess ×1
urllib ×1
urllib2 ×1
utf-8 ×1
yajl ×1