whenever I run the server or executing any commands in the terminal this error is showing in the terminal. The server is running and the webpage is working fine but when I quit the server or run any commands(like python manage.py migrate) this error is showing.
`Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
September 21, 2020 - 12:42:24
Django version 3.0, using settings 'djangoblog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:Python37libsite-packagesdjangocoremanagement__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:Python37libsite-packagesdjangocoremanagement__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:Python37libsite-packagesdjangocoremanagementbase.py", line 341, in run_from_argv
connections.close_all()
File "C:Python37libsite-packagesdjangodbutils.py", line 230, in close_all
connection.close()
File "C:Python37libsite-packagesdjangoutilsasyncio.py", line 24, in inner
return func(*args, **kwargs)
File "C:Python37libsite-packagesdjangodbbackendssqlite3base.py", line 261, in close
if not self.is_in_memory_db():
File "C:Python37libsite-packagesdjangodbbackendssqlite3base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "C:Python37libsite-packagesdjangodbbackendssqlite3creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
`
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Comments
I got the following error when running pytest
:
> needquote = (" " in arg) or ("t" in arg) or not arg E TypeError: 'WindowsPath' object is not iterable TypeError: argument of type 'WindowsPath' is not iterable ...Miniconda3envsmanubot-devlibsubprocess.py:461: TypeError
I fixed this by converting path to str:
Line 461: needquote = (" " in str(arg)) or ("t" in str(arg)) or not str(arg)
Line 465: for c in str(arg):
.. according to this suggestion.
My programming background is pretty limited and I am not sure whether this solution fits for all, thus I am sharing it here (and not directly committing).
Thanks for reporting this @Sieboldianus.
If we want to support Windows or test the feasibility of Windows support, we could consider adding AppVeyor for continuous integration testing. I haven’t checked recently whether Travis supports Windows, but not too long ago I saw recommendations for Travis + AppVeyor for testing multiple platforms.
@dhimmel: Many thanks, please feel free to just PR this!
@agitter: I think getting Manubot to run on Windows is not a big deal. I got stuck with another bug towards the end, when running sh build/build.sh
with the example Manubot-Rootstock, where I got a compilation error for generating the shortlink to images
folder in ...output
. I investigated it shortly and think it has something to do with how shortlinks are handled in Windows compared to POSIX systems, but I did not have more time.
dhimmel
added a commit
to dhimmel/manubot
that referenced
this issue
May 30, 2018
Closes manubot#34
Thanks Alexander Dunkel for reporting the issue.
#35 now tests this repository on windows, so the manubot
CLI should be windows compatible.
@Sieboldianus setting up the travis infrastructure of manubot-rootstock currently doesn’t work on Windows due to an upstream issue. Looks like you’re hitting another issue, perhaps related to the symbolic links. Anyways, if you elaborate about your desired use case, perhaps we can support it or find an acceptable workaround.
dhimmel
added a commit
to dhimmel/manubot
that referenced
this issue
Feb 19, 2020
Содержание
- TypeError: argument of type ‘WindowsPath’ is not iterable #6894
- Comments
- AhmedSalam22 commented Aug 28, 2020
- AhmedSalam22 commented Aug 28, 2020
- FinalAngel commented Aug 31, 2020
- AhmedSalam22 commented Aug 31, 2020
- FinalAngel commented Aug 31, 2020
- AhmedSalam22 commented Aug 31, 2020
- goutnet commented May 19, 2022
- TypeError: argument of type ‘WindowsPath’ is not iterable #34
- Comments
- Sieboldianus commented May 29, 2018 •
- dhimmel commented May 29, 2018
- agitter commented May 29, 2018
- Sieboldianus commented May 30, 2018
- dhimmel commented Jun 3, 2018
TypeError: argument of type ‘WindowsPath’ is not iterable #6894
this error face me when I am trying install Django-cms manually
http://docs.django-cms.org/en/latest/how_to/install.html
I use Django 3.0 and django-cms-3.7.4
The text was updated successfully, but these errors were encountered:
I have solved the problem in setting.py I replaced
‘NAME’: BASE_DIR / ‘db.sqlite3’,
with
‘NAME’: str(BASE_DIR / ‘db.sqlite3’),
👍 did you find a reference like this in the documentation? Because we normally recommend os.path.join()
No, you should put this in documentation
That is in the documentation, to use os.path.join() that is. 🙂
there is no mention in the documentation about to use os.path.join() just only for media root but there is no mention to use it in the database and I have solved the problem in setting.py I replaced
‘NAME’: BASE_DIR / ‘db.sqlite3’,
with
‘NAME’: str(BASE_DIR / ‘db.sqlite3’),
this point in documentation should be clear for a newbie like me and Thank’s for replay
merged in develop (and will be released on 3.9.0) see #6919
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
TypeError: argument of type ‘WindowsPath’ is not iterable #34
I got the following error when running pytest :
I fixed this by converting path to str:
Line 461: needquote = (» » in str(arg)) or («t» in str(arg)) or not str(arg)
Line 465: for c in str(arg):
My programming background is pretty limited and I am not sure whether this solution fits for all, thus I am sharing it here (and not directly committing).
The text was updated successfully, but these errors were encountered:
Refs https://bugs.python.org/issue33617. wow, a pretty annoying bug for core python. Looks like there’s a PR open to fix it, but that won’t be available until at least 3.8. So let’s fix this before then.
I’d suggest wrapping the following pathlib.Path objects in str :
@Sieboldianus do you want to make a PR to do that?
I’m not sure whether there will be other issues with running the manubot package on windows. I don’t think we’ve decided whether this package officially supports windows, but if it’s just a few small fixes like this, we might as well for the time being.
Thanks for reporting this @Sieboldianus.
If we want to support Windows or test the feasibility of Windows support, we could consider adding AppVeyor for continuous integration testing. I haven’t checked recently whether Travis supports Windows, but not too long ago I saw recommendations for Travis + AppVeyor for testing multiple platforms.
@dhimmel: Many thanks, please feel free to just PR this!
#35 now tests this repository on windows, so the manubot CLI should be windows compatible.
@Sieboldianus setting up the travis infrastructure of manubot-rootstock currently doesn’t work on Windows due to an upstream issue. Looks like you’re hitting another issue, perhaps related to the symbolic links. Anyways, if you elaborate about your desired use case, perhaps we can support it or find an acceptable workaround.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Created on 2020-08-27 14:25 by rasjani, last changed 2022-04-11 14:59 by admin.
Messages (5) | ||
---|---|---|
msg375993 — (view) | Author: Jani Mikkonen (rasjani) | Date: 2020-08-27 14:25 |
Following code: ``` from pathlib import Path import os import subprocess dir_name = os.environ.get("WORKSPACE", None) or "." output_directory = Path(dir_name) / "results" res = subprocess.run(["mytest", "--output", output_directory]) ``` Works on macos and linux but on windows, this causes "TypeError: argument of type 'WindowsPath' is not iterable" at https://github.com/python/cpython/blob/master/Lib/subprocess.py#L568 (line is different, depending on the actual python release but i guess that gives the idea where it is).. Quick test to check if i can do `" " in Path("/tmp")` on posix platforms shows the same exception but with PosixPath type but apparently this sort of check does not happen on those platforms as the example code works fine there. It would be nice to be able to pass path objects to subprocess api calls also in windows without explicitly casting the object into string before passing it as argument. |
||
msg375995 — (view) | Author: Karthikeyan Singaravelan (xtreak) * | Date: 2020-08-27 14:40 |
See also https://bugs.python.org/issue31961 |
||
msg376024 — (view) | Author: Jani Mikkonen (rasjani) | Date: 2020-08-28 08:59 |
@xtreak I went thru the comments of the report you linked. It definitely looks like the discussion was related but it didnt really fix the issue here. https://bugs.python.org/issue31961#msg311775 without trying out, that comment actually touches the underlying issue, on windows, list2cmdline throws that typeerror because iterated argument list (output_directory in my example) is WindowsPath and thus not iterable and and testing the arg with "in" operator fails .. |
||
msg376043 — (view) | Author: Serhiy Storchaka (serhiy.storchaka) * | Date: 2020-08-28 16:10 |
I do not understand how you get this result. At that line of code arg can only be string, because it is a result of os.fsdecode(). Are you sure that you use Python version which includes issue31961 changes? What exactly Python version do you use? |
||
msg376760 — (view) | Author: Terry J. Reedy (terry.reedy) * | Date: 2020-09-12 01:28 |
I closed #41753 as a duplicate of this. On that issue, Eryk Sun said "The underlying subprocess.Popen class was updated in 3.8 to support path-like objects in `args` (with shell=False) and `executable` on Windows [1]. This change was not backported to 3.6 and 3.7." The latter is because 3.6 and 3.7 only get security patches. Jani, please verify that this is still an issue with 3.8 and/or 3.9. |
History | |||
---|---|---|---|
Date | User | Action | Args |
2022-04-11 14:59:35 | admin | set | github: 85815 |
2020-09-12 01:28:59 | terry.reedy | set | nosy: + terry.reedy messages: |
2020-09-12 01:25:10 | terry.reedy | link | issue41753 superseder |
2020-08-28 16:10:55 | serhiy.storchaka | set | messages: + msg376043 |
2020-08-28 08:59:48 | rasjani | set | messages: + msg376024 |
2020-08-27 14:40:41 | xtreak | set | nosy: + serhiy.storchaka, xtreak messages: + msg375995 |
2020-08-27 14:25:18 | rasjani | create |
Код, который я пытался запустить:
import numpy as np
import os
import cv2
import matplotlib.pyplot as plt
from os import listdir
from pathlib import Path
all_images = list(Path(r'D:/face/train').glob('**/*.jpg'))
np.array([np.array(cv2.imread(str(file))).flatten() for file in all_images])
Path = r'D:facetrain'
print(all_images[0])
Вывод: D: face train F0002 MID1 P00009_face3.jpg
train_images = ([x for x in all_images if val_families not in x])
val_images = ([x for x in all_images if val_families in x])
Я получаю следующую ошибку.
TypeError Traceback (most recent call last)
<ipython-input-8-8de97a2e12c1> in <module>
----> 1 train_images = ([x for x in all_images if val_families not in x])
2 val_images = ([x for x in all_images if val_families in x])
<ipython-input-8-8de97a2e12c1> in <listcomp>(.0)
----> 1 train_images = ([x for x in all_images if val_families not in x])
2 val_images = ([x for x in all_images if val_families in x])
TypeError: argument of type 'WindowsPath' is not iterable
Прежде всего, я не использовал класс Path, вместо этого я использовал следующую команду
all_images = glob(train_folders_path + "*/*/*.jpg")
print(all_images[0])
Но здесь я получал ошибку индекса. позже я импортировал Path и попробовал первый код, который дал мне желаемый результат. но я получаю ошибку, как я уже упоминал в следующей строке. Пожалуйста, помогите мне решить эту проблему.
1 ответ
Лучший ответ
здесь я получал ошибку индекса.
glob
возвращает генератор, а не контейнер. Вы можете перебирать результаты glob, но вы можете сделать это только один раз, и вы не можете использовать индекс для получения первоначального результата.
Если вы хотите использовать результаты несколько раз, или выберите первый с помощью [0]
, затем используйте list( ... )
, как показал ваш первый пример кода. Это будет перебирать результаты и сохранять их в list
контейнер, который вы можете повторно использовать или индексировать по своему усмотрению.
В качестве альтернативы вы можете использовать next( ... )
для доступа только к исходный результат, но, похоже, это не то, что вы хотите здесь.
РЕДАКТИРОВАТЬ
что означает, что этот путь WindowsPath не повторяется?
list
, полученный из glob
, имеет несколько элементов, и каждый из этих элементов — Путь. Вы не можете перебирать Path
, точно так же, как вы не можете перебирать int
. Вы, конечно, можете перебирать list
из Path
сек, или более list
из int
сек.
Вы можете превратить Path
в str
и перебрать его, как в примере ниже, но это не то, что вам нужно. Обычно вам нужно open(path, 'r')
и повторить поверх того , который выводит строки из текстового файла, по одной строке за раз.
>>> from pathlib import Path
>>>
>>> path = Path('foo')
>>> path
PosixPath('foo')
>>>
>>> for x in path:
... print(x)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'PosixPath' object is not iterable
>>>
>>> for x in str(path):
... print(x)
...
f
o
o
>>>
1
J_H
26 Окт 2019 в 18:58
Add Answer
|
View In TPC Matrix
Technical Problem Cluster First Answered On
June 3, 2021
Popularity
9/10
Helpfulness
10/10
Contributions From The Grepper Developer Community
Contents
Code Examples
Related Problems
TPC Matrix View Full Screen
TypeError: argument of type ‘WindowsPath’ is not iterable
Comment
5
Popularity
9/10 Helpfulness
10/10
Language
python
Source: Grepper
Tags: iterable
python
Contributed on Jun 03 2021
Talented Tamarin
1 Answers Avg Quality 10/10
Message
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) (V8-based) TypeError: x is not iterable (Firefox) TypeError: undefined is not a function (near
Error type
Что пошло не так?
Examples
Деструктуризация массива неитерабельного
const myobj = { arrayOrObjProp1: {}, arrayOrObjProp2: [42] }; const { arrayOrObjProp1: [value1], arrayOrObjProp2: [value2] } = myobj; console.log(value1, value2);
Неитерируемый объект может оказаться undefined
в некоторых средах выполнения.
Изменение свойств объекта
В JavaScript объекты Object
не являются итерируемыми, если они не реализуют итерируемый протокол . Поэтому вы не можете использовать for...of
для перебора свойств объекта.
const obj = { France: 'Paris', England: 'London' }; for (const p of obj) { }
Вместо этого вы должны использовать Object.keys
или Object.entries
, чтобы перебирать свойства или записи объекта.
const obj = { France: 'Paris', England: 'London' }; for (const country of Object.keys(obj)) { const capital = obj[country]; console.log(country, capital); } for (const [country, capital] of Object.entries(obj)) { console.log(country, capital); }
Другой вариант для этого варианта использования может заключаться в использовании Map
:
const map = new Map; map.set('France', 'Paris'); map.set('England', 'London'); for (const country of map.keys()) { const capital = map.get(country); console.log(country, capital); } for (const capital of map.values()) { console.log(capital); } for (const [country, capital] of map.entries()) { console.log(country, capital); }
перемалывание через генератор
Генераторы — это функции, которые вы вызываете для создания итерируемого объекта.
function* generate(a, b) { yield a; yield b; } for (const x of generate) { console.log(x); }
Когда они не вызываются, объект Function
, соответствующий генератору, является вызываемым, но не повторяемым. Вызов генератора создает итеративный объект, который будет перебирать значения, полученные во время выполнения генератора.
function* generate(a, b) { yield a; yield b; } for (const x of generate(1, 2)) { console.log(x); }
Итерация по пользовательской итерационной таблице
Пользовательские итерации могут быть созданы путем реализации метода Symbol.iterator
. Вы должны быть уверены, что ваш метод итератора возвращает объект, который является итератором, то есть у него должен быть следующий метод.
const myEmptyIterable = { [Symbol.iterator]() { return []; } } Array.from(myEmptyIterable);
Вот правильная реализация:
const myEmptyIterable = { [Symbol.iterator]() { return [][Symbol.iterator]() } } Array.from(myEmptyIterable);
See also
- iterable protocol
Object.keys
Object.entries
Map
- generators
- for…of
JavaScript
-
SyntaxError: объявление в начале цикла for-of не может иметь инициализатор
Объявление исключения JavaScript в заголовке цикла for-of не может иметь инициализатор» возникает, когда содержит такое выражение (const 0 iterable).
-
TypeError: недопустимый операнд «экземпляр» «х»
Исключение JavaScript «недопустимый операнд экземпляра» возникает, когда оператор правых операндов не используется с объектом конструктора, т.е.
-
Синтаксическая ошибка:JSON.parse:плохой парсинг
Исключения JavaScript,выбрасываемые JSON.parse(),возникают,когда строка не была разобрана JSON.parse()разбирает строку как Обе строки будут выбрасывать SyntaxError:
-
Синтаксическая ошибка:Некорректный формальный параметр
Исключение JavaScript «искаженный формальный параметр» возникает, когда список аргументов вызова конструктора Function() каким-то образом недействителен.