How can I check if an object is a file with isinstance()? - python

How can I check if an object is a file?
>>> f = open("locus.txt", "r")
>>> type(f)
<class '_io.TextIOWrapper'>
>>> isinstance(f, TextIOWrapper)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
isinstance(f, TextIOWrapper)
NameError: name 'TextIOWrapper' is not defined
>>> isinstance(f, _io.TextIOWrapper)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
isinstance(f, _io.TextIOWrapper)
NameError: name '_io' is not defined
>>> isinstance(f, _io)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
isinstance(f, _io)
NameError: name '_io' is not defined
>>>
I have the variable f that is a text file. When I print the type of f the Python3 interpreter shows '_io.TextIOWrapper', but if I check it with isinstance() function throws exception: NameError.

_io is the C implementation for the io module. Use io.IOBase for direct subclasses, after importing the module:
>>> import io
>>> f = open("tests.py", "r")
>>> isinstance(f, io.IOBase)
True

Related

TypeError: NoneType object is not iterable

When I am iterating through my variable it gives me an error which I show as below.
Traceback (most recent call last):
File "C:\Users\ZHEN YUAN\Desktop\东航第一步\wen2.py", line 13, in <module>
for i in Names:
TypeError: 'NoneType' object is not iterable
Your function wenjian() does not have any return statements, so it will always return None, by default. That's why Names = wenjian(file) assigns the value None to Names, and so you can't iterate over Names with the for loop.
import os
def wenjian(file):
for root,dirs,files in os.walk(file):
for file in files:
filename = os.path.join(root,file)
print (filename[-28:])
file = ("C:\Users\ZHEN YUAN\Desktop\东航try")
Names = wenjian(file)
for i in Names:
print (i[1])
PS C:\Users\ZHEN YUAN> & python "c:/Users/ZHEN YUAN/Desktop/东航第一步/wen2.py"
\Desktop\东航try\C2002455.xlsx
Traceback (most recent call last):
File "c:/Users/ZHEN YUAN/Desktop/东航第一步/wen2.py", line 14, in <module>
for i in Names:
TypeError: 'function' object is not iterable

python uiautomator TypeError: 'AutomatorDeviceObject' object is not callable

Above are the uiautomator object viewer screenshots with properties. I am using python package uiautomator installed through pip install uiautomator. I am trying to access the three-dotted settings button through UI automator objects. I have tried using the documentation listed at https://github.com/xiaocong/uiautomator#handler
Here is the code and error:
import uiautomator as uia
d = uia.device() #below all are my attempts
>>> d(resourceId="com.android.camera2:id/three_dots").clickable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle").clickable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="id/mode_options_toggle")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle").clickable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle").clickable()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle", className="com.android.camera2")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle", className="com.android.camera2").clcik()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle", className="com.android.camera2").click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle", className="com.android.camera2").click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(package="com.android.camera2")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/progress_overlay")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/progress_overlay")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/progress_overlay")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className="android.view.View")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className="android.view.View").child(className="android.widget.LinearLayout", resourceId="com.android.camera2:id/mode_options_toggle")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className="android.view.View").child(className="android.widget.LinearLayout", resourceId="com.android.camera2:id/mode_options_toggle").click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(text="").info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d.info
{u'contentDescription': u'', u'checked': False, u'clickable': False, u'scrollable': False, u'text': u'', u'packageName': u'com.android.camera2', u'selected': False, u'enabled': True, u'bounds': {u'top': 0, u'left': 0, u'right': 1440, u'bottom': 2560}, u'className': u'android.widget.FrameLayout', u'focusable': False, u'focused': False, u'checkable': False, u'resourceName': None, u'longClickable': False, u'visibleBounds': {u'top': 0, u'left': 0, u'right': 1440, u'bottom': 2392}, u'childCount': 2}
>>> d(packageName=u'com.android.camera2).info
File "<stdin>", line 1
d(packageName=u'com.android.camera2).info
^
SyntaxError: EOL while scanning string literal
>>> d(packageName=u'com.android.camera2').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className=u'com.android.camera2').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className=u'com.android.camera2').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className=u'').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className=u'android.widget.FrameLayout').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className="android.widget.FrameLayout").info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>>
After all attempts, I am still not able to access the any of the UI objects. Please let me know what am I missing here?
Change:
import uiautomator as uia
d = uia.device()
To:
import uiautomator as uia
d = uia.device
This should solve your problem.
It is happening because you're calling the function device() inside a variable. So "d" is not a function, but use a function to receive a value.
When we call a function using parenthesis Python understands we are calling it and using this result on your variable "d". That's the reason why you're facing "object is not callable", because no object is being passed as parameter to "device()".
When we don't use parenthesis we not call the function, we make a reference to it and the parameters will be passed when we call it.
Hope it helps!
Not a solution to your problem but an alternative: using AndroidViewClient/culebra you can run
culebra -uG -o camera-options.py
once you have the window you can click on the options dots
see the result immediately
and at the same time, the script containing the code to reproduce this action will be generated
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2017 Diego Torres Milano
Created on 2017-11-24 by Culebra v13.5.2
__ __ __ __
/ \ / \ / \ / \
____________________/ __\/ __\/ __\/ __\_____________________________
___________________/ /__/ /__/ /__/ /________________________________
| / \ / \ / \ / \ \___
|/ \_/ \_/ \_/ \ o \
\_____/--<
#author: Diego Torres Milano
#author: Jennifer E. Swofford (ascii art snake)
'''
import re
import sys
import os
try:
sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
pass
from com.dtmilano.android.viewclient import ViewClient
TAG = 'CULEBRA'
_s = 5
_v = '--verbose' in sys.argv
kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
vc = ViewClient(device, serialno, **kwargs2)
#vc.dump(window='-1') # FIXME: seems not needed
vc.dump(window=-1)
vc.findViewWithContentDescriptionOrRaise(u'''Options''').touch()

Django FieldFile cannot write on the first open

I am trying to write to a FieldFile of an instance of a model:
class SourceFile(models.Model):
file_name = models.CharField('File Name', max_length = 100, unique=True)
import_time = models.DateTimeField('Import Time', auto_now_add = True)
local_link = models.FileField(upload_to="ozio/uploaded_files/%Y")
Having no problem when I create the file with:
source_file = SourceFile.objects.create(file_name = source_file_name)
source_file.local_link.save(source_file.file_name, ContentFile('LINE1'))
However when I tried to append new lines:
source_file.local_link.open('a') # Open as append mode
source_file.local_link.write('LINE2')
It complains:
Traceback (most recent call last):
File "<console>", line 1, in <module>
io.UnsupportedOperation: write
When close it and reopen, everything looks ok. Grateful for any suggestion.
>>> source_file, created = SourceFile.objects.get_or_create(file_name = 'Manual.2014.Q2.csv')
>>> source_file.local_link
<FieldFile: ozio/uploaded_files/2014/Manual.2014.Q2.csv>
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE2')
Traceback (most recent call last):
File "<console>", line 1, in <module>
io.UnsupportedOperation: write
>>> source_file.local_link.close()
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE2')
5
>>> source_file.local_link.close()
>>> source_file, created = SourceFile.objects.get_or_create(file_name = 'Manual.2014.Q2.csv')
>>> source_file.local_link.open('a')
>>> source_file.local_link.close()
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE3')
5
>>> source_file.local_link.close()
>>>

How to see complete traceback?

I have added an assert(0) in a function to understand the sequence of function calls to this function.
Ex:
def my_func():
...lines of code...
assert(0)
...more lines of code...
The logs show only this:
Traceback (most recent call last):
File "/var/www/folder/file.py", line 273, in my_func
assert(0)
AssertionError
I want to see the complete call trace - Example: first_func -> second_func -> my_func
I tried traceback library but it is showing me the same stacktrace.
Please let me know what I am missing here.
Use traceback module for this. I.e.
>>> import traceback
>>> def my_func():
... my_other_func()
...
>>> def my_other_func():
... my_third()
...
>>> def my_third():
... print "Stack"
... traceback.print_stack()
... print "Extracted"
... print repr(traceback.extract_stack())
...
>>>
>>> my_func()
Stack
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in my_func
File "<stdin>", line 2, in my_other_func
File "<stdin>", line 3, in my_third
Extracted
[('<stdin>', 1, '<module>', None),
('<stdin>', 2, 'my_func', None),
('<stdin>', 2, 'my_other_func', None),
('<stdin>', 5, 'my_third', None)]
>>>

Python: saving objects and using pickle. Error using pickle.dump

Hello I have an Error and I don´t the reason:
>>> class Fruits:pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> import pickle
>>> filehandler = open("Fruits.obj",'w')
>>> pickle.dump(banana,filehandler)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line 1354, in dump
Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
TypeError: must be str, not bytes
>>>
I don´t know how to solve this error because I don´t understand it.
Thank you so much.
You have to open your filehandler in binary mode, use wb instead of w:
filehandler = open(b"fruits.obj","wb")

Categories