import ftplib
import urllib2
import os
import logging
logger = logging.getLogger('ftpuploader')
hdlr = logging.FileHandler('ftplog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
FTPADDR = "some ftp address"
def upload_to_ftp(con, filepath):
try:
f = open(filepath,'rb') # file to send
con.storbinary('STOR '+ filepath, f) # Send the file
f.close() # Close file and FTP
logger.info('File successfully uploaded to '+ FTPADDR)
except, e:
logger.error('Failed to upload to ftp: '+ str(e))
Run Code Online (Sandbox Code Playgroud)
这似乎不起作用,我得到语法错误,这是什么正确的方法来记录文件的所有类型的异常
我有一个嵌套字典.是否只有一种方法可以安全地获得价值?
try:
example_dict['key1']['key2']
except KeyError:
pass
Run Code Online (Sandbox Code Playgroud)
或者python有一个像get()嵌套字典的方法?
这是将python"with"语句与try-except块结合使用的正确方法吗?:
try:
with open("file", "r") as f:
line = f.readline()
except IOError:
<whatever>
Run Code Online (Sandbox Code Playgroud)
如果是,那么考虑旧的做事方式:
try:
f = open("file", "r")
line = f.readline()
except IOError:
<whatever>
finally:
f.close()
Run Code Online (Sandbox Code Playgroud)
这里"with"语句的主要好处是我们可以摆脱三行代码吗?对于这个用例来说,这似乎并不令我感到高兴(尽管我理解"with"语句还有其他用途).
编辑:上面两个代码块的功能是否相同?
EDIT2:前几个答案一般性地讨论了使用"with"的好处,但这些似乎在边缘效益.我们已经(或应该已经)多年来明确地调用f.close().我想一个好处是,草率编码器将从使用"with"中受益.
我在try块中的代码有问题.为了方便起见,这是我的代码:
try:
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
except:
pass
Run Code Online (Sandbox Code Playgroud)
这样的事情可能吗?
如果我运行代码:
connection = manager.connect("I2Cx")
Run Code Online (Sandbox Code Playgroud)
程序崩溃并报告KeyError,因为I2Cx不存在(它应该是I2C).
但如果我这样做:
try:
connection = manager.connect("I2Cx")
except Exception, e:
print e
Run Code Online (Sandbox Code Playgroud)
它没有为e打印任何东西.我希望能够打印抛出的异常.如果我尝试使用除零操作来执行相同操作,则会在两种情况下都正确捕获并报告.我在这里错过了什么?
可能重复:
LINQ在两个列表中找到差异
我想找到2系列之间的区别.所以我Except在LINQ语句中使用.但Except似乎只有在第一个集合长于第二个集合时才有效.例如,即使2个集合不同,也不会返回任何结果.
double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };
IEnumerable<double> onlyInFirstSet = numbers2.Except(numbers1);
Run Code Online (Sandbox Code Playgroud)
任何人都可以确认是否是这种情况?如果是这样,在编写查询之前是否必须检查集合长度,因为我不知道哪个集合在编译时会更大.
编辑
我想我的问题并不清楚.我不关心哪个集合包含什么.我只是想找到两个系列之间的区别.我怎样才能做到这一点?
我的上面有一个SyntaxError,除了:
try:
opts, args = getopt.getopt(sys.argv[1:], 'P:D:H:d:u:p:nvhmJi:c:Ml:TB:',
['host=', 'port=', 'directory=', 'user=', 'password=',
'daemon=', 'noauth', 'help', 'verbose', 'mysql',
'icounter=', 'config=', 'nolock', 'nomime', 'loglevel', 'noiter',
'baseurl='])
except getopt.GetoptError, e:
print usage
print '>>>> ERROR: %s' % str(e)
sys.exit(2)
Run Code Online (Sandbox Code Playgroud)
我收到错误:
File "main.py", line 199
except getopt.GetoptError, e:
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
任何人都有任何想法?
我上课了:
class ThisClass
{
private string a {get; set;}
private string b {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我想使用Linq的Intersect和Except方法,即:
private List<ThisClass> foo = new List<ThisClass>();
private List<ThisClass> bar = new List<ThisClass>();
Run Code Online (Sandbox Code Playgroud)
然后我分别填写两个列表.我想做,例如(我知道这是不对的,只是伪代码),如下:
foo[a].Intersect(bar[a]);
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
我有这个python代码:
import os
try:
os.system('wrongcommand')
except:
print("command does not work")
Run Code Online (Sandbox Code Playgroud)
代码打印:
wrongcommand: command not found
Run Code Online (Sandbox Code Playgroud)
而不是command does not work.有谁知道为什么它不打印我的错误信息?
我是Python的初学者,并且一直在测试不同类型的示例代码.当我开始使用Python3而不是2.7; 我遇到了语法错误,但我不明白如何修复该错误.
File "app.py", line 101
except InvalidUserPass, e:
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
这里有更多代码来提供一些上下文:
@app.route('/login/', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
session['username'] = request.form['username']
session['password'] = request.form['password']
try:
# use reddit_api's login
r.login(user=session['username'], password=session['password'])
except InvalidUserPass, e:
error = 'Incorrect username or password. '
if not error:
subreddits = r.user.get_my_reddits(limit=25)
my_reddits = []
for i in range(25):
my_reddits.append(subreddits.next().display_name)
session['my_reddits'] = my_reddits
return redirect(url_for('index'))
return render_template('login.html', error=error)
Run Code Online (Sandbox Code Playgroud) except ×10
python ×8
try-catch ×4
exception ×2
linq ×2
c# ×1
dictionary ×1
finally ×1
intersect ×1
logging ×1
methods ×1
os.system ×1
python-3.x ×1
syntax-error ×1