I'm trying to run a code:
import os
from os import listdir
for f in sorted(os.listdir("/path")):
if f in f.startswith("20"):
for f in sorted(os.listdir(f)):
if f.endswith(".txt"):
pass
else:
try:
os.system("/path/script.py %s" % f)
except:
pass
I have received this error:
Traceback (most recent call last):
File "files_correct_phase.py", line 5, in <module>
if f in f.startswith("20"):
TypeError: argument of type 'bool' is not iterable
code here
I ran it inside the python prompt and it worked fine after line 5, but when I run it as
python python_script.py
in the command line, it gives me this error. I would be grateful for any advice and/or help.
(Python version 2.7.6)
if f in f.startswith("20"):
is not valid. startswith returns a bool the in keyword trys to check for containment inside your bool. That only works for iterables (which bool is not). You probably want:
if f.startswith("20"):
Related
Consider the following MWE:
import hashlib
def tstfun(h: hashlib._hashlib.HASH):
print(h)
h = hashlib.md5()
tstfun(h)
# reveal_type(h)
Running this as-is yields - no surprise:
$ python mypytest.py
<md5 _hashlib.HASH object # 0x7fa645dedd90>
But checking this with mypy fails with:
$ mypy mypytest.py
mypytest.py:4: error: Name 'hashlib._hashlib.HASH' is not defined
Found 1 error in 1 file (checked 1 source file)
Now, revealing the type on h (commenting in that reveal_type line):
$ mypy mypytest.py
mypytest.py:4: error: Name 'hashlib._hashlib.HASH' is not defined
mypytest.py:10: note: Revealed type is 'hashlib._Hash'
Found 1 error in 1 file (checked 1 source file)
Well, ok, then changing the type hint from hashlib._hashlib.HASH to hashlib._Hash:
$ python mypytest.py
Traceback (most recent call last):
File "/radarugs/hintze/s4-cnc-tools/mypytest.py", line 4, in <module>
def tstfun(h: hashlib._HASH):
AttributeError: module 'hashlib' has no attribute '_HASH'
$ mypy mypytest.py
mypytest.py:4: error: Name 'hashlib._HASH' is not defined
Found 1 error in 1 file (checked 1 source file)
...which is the worst outcome.
How to check if the type stubs for the hashlib are correctly found and used by mypy? What else to check? What do I get wrong?
According to the traceback, you used hashlib._HASH.
With this code:
import hashlib
def tstfun(h: hashlib._Hash):
print(h)
h = hashlib.md5()
tstfun(h)
Mypy reports: Success: no issues found in 1 source file
Using hashlib._Hash is correct, but you also need to from __future__ import annotations if you don't want to use quotes. See https://github.com/python/typeshed/issues/2928
from __future__ import annotations
import hashlib
def tstfun(h: hashlib._Hash):
print(h)
h = hashlib.md5()
tstfun(h)
N.B.: __future__.annotations is available starting in python 3.7.0b1. See https://docs.python.org/3/library/__future__.html
I used indentation method in the code but it throws a error. Need solution please. My python version is Python 2.7.15+
Code:
import textwrap
s = 'hello\n\n \nworld'
s1 = textwrap.indent(text=s, prefix=' ')
print (s1)
print ("\n")
s2 = textwrap.indent(text=s, prefix='+ ', predicate=lambda line: True)
print (s2)
Code is taken from geeksforgeeks
Output Error:
python Textwrap5.py
Traceback (most recent call last):
File "Textwrap5.py", line 4, in <module>
s1 = textwrap.indent(text=s, prefix=' ')
AttributeError: 'module' object has no attribute 'indent'
It might be that your file is located in a directory called textwrap or you have other file called textwrap in the same or parent directory.
Try changing the directory name or the file and see if it works
Python2.7, textwrap doesn't have indent function available.
Either use initial_indent or subsequent_indent as per your requirement OR upgrade to Python3.x
I want to access a shell environment variable in my python script.
I am trying this
import os
print os.environ.get["HOME"]
I get this error when I am executing in python
(I am getting the same error in bash also)
Traceback (most recent call last):
File "C:\Users\sraparim\Desktop\GitHub issues\issue #1187\test.py", line 54, in <module>
print os.environ.get["HOME"]
TypeError: 'instancemethod' object has no attribute '__getitem__'
[Finished in 0.2s with exit code 1]
[shell_cmd: python -u "C:\Users\sraparim\Desktop\GitHub issues\issue #1187\test.py"]
[dir: C:\Users\sraparim\Desktop\GitHub issues\issue #1187]
[path: C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\WebEx\Productivity Tools;C:\Program Files (x86)\Cisco\OSD-ShellApplications;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Program Files\PuTTY\;C:\Python27\Scripts;C:\Python27;C:\Python27]
Please help...
get() is a method on the environ object; use parentheses instead of brackets:
print os.environ.get('HOME')
or brackets without get, which implicitly calls __getitem__():
print os.environ['HOME']
pytest has this example in the monkeypatching docs:
import os.path
def getssh(): # pseudo application code
return os.path.join(os.path.expanduser("~admin"), '.ssh')
def test_mytest(monkeypatch):
def mockreturn(path):
return '/abc'
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
x = getssh()
assert x == '/abc/.ssh'
When I remove the path argument from the mockreturn function, I get the error
def getssh(): # pseudo application code
> return os.path.join(os.path.expanduser("~admin"), '.ssh')
E TypeError: mockreturn() takes 0 positional arguments but 1 was given
I don't understand what is providing that positional argument?
Also, when I reimplement the same thing for pathlib.Path.home() I cannot have this argument path there, otherwise it won't work. Unfortunately, the documentation does not say anything about that ominous path argument.
Any illumination for what magic is happening here would be very helpful!
You're trying to replace os.path.expanduser that takes one argument with a mock that doesn't take arguments at all which results to an error when called.
Under the hood monkeypatch.setattr uses builtin setattr so the original version is basically doing following which works since both expanduser and mock take single argument:
>>> import os.path
>>> def mock(path):
... return '/abc'
...
>>> setattr(os.path, 'expanduser', mock)
>>> os.path.expanduser('~admin')
'/abc'
Now if you try to replace expanduser with a method that doesn't take arguments and keep calling it the same way you'll get an error:
>>> setattr(os.path, 'expanduser', mock)
>>> os.path.expanduser('~admin')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: mock() takes 0 positional arguments but 1 was given
Note that you'll get exactly the same error if you try to call mock directly:
>>> mock('~admin')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: mock() takes 0 positional arguments but 1 was given
I'm working with xml.etree.cElementTree, and regarding to official documentation - want find element in Element:
$ python --version
Python 2.7.8
My script:
#!/usr/bin/env python
import os, re
import xml.etree.ElementTree as ET
XML_FILE = '/cygdrive/****.csproj'
try:
tree = ET.ElementTree(file=XML_FILE)
root = tree.getroot()
print type(root)
for item in root.iter(tag='OutputPath'):
print item.tag, item.attrib, item.text
....
But when I run it - have an error:
$ ./xm_par.py
<type 'Element'>
Traceback (most recent call last):
File "./xm_par.py", line 21, in <module>
for item in root.iter(tag='OutputPath'):
TypeError: iter() takes no keyword arguments
What I'm miss here?
This is a known bug; the C accelerated version of the API is missing support for the tag parameter as a keyword argument. See issue #16849:
Element.{get,iter} doesn't handle keyword arguments when using _elementtree C accelerator.
The bug was fixed in Python 3.3 and up but not in Python 2.7 yet.
You can omit the keyword and pass in the argument as a positional instead:
for item in root.iter('OutputPath'):
Demo:
>>> import xml.etree.cElementTree as ET
>>> tree = ET.fromstring('''\
... <root>
... <OutputPath></OutputPath>
... </root>
... ''')
>>> tree.iter(tag='OutputPath')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: iter() takes no keyword arguments
>>> tree.iter('OutputPath')
<generator object iter at 0x1045cc5a0>