Source must be saved ok to save python

Saving a Python 2.7 script that contains Arabic

I’m having a weird issue. I’m working on a Twitter-Tweepy-MySQL collection project. I’m totally happy with my script. If I run it collecting against «#London», for example — no problem. However, when I try collect on a non-Latin hashtag (eg «#מזל_טוב»), I can’t even save the script, let alone run it. I hit Ctrl + S — doesn’t save. I try run the script — I get «Source Must Be Saved Ok to Save?», hit Ok — nothing happens. This happens with both Arabic and Hebrew hashtags, so I can only think there’s a unicode issue here — but when I collect against a Latin hashtag which coincidentally produces non-Latin alphabet results, they’re printed & saved to MySQL without a problem. Very grateful for any pointers.
Robin Script follows:

from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener import MySQLdb import time import json conn = MySQLdb.connect ('nyub', 'nyub', 'nyub', 'nyub', charset='utf8') c = conn.cursor() ckey = "'nyub'" csecret = "'nyub'" atoken = "-'nyub'" asecret = "'nyub'" class listener (StreamListener): def on_data(self, data): try: tweet = json.loads(data) created_at = tweet ["created_at"] identity = tweet ["id"] text = tweet ["text"] status_reply = tweet ["in_reply_to_status_id"] user_reply = tweet ["in_reply_to_user_id"] screen_name_reply = tweet ["in_reply_to_screen_name"] user_id = tweet ["user"]["id"] user_screen_name = tweet["user"]["screen_name"] user_location = tweet["user"]["location"] user_url = tweet["user"]["url"] user_description = tweet["user"]["description"] user_followers = tweet["user"]["followers_count"] user_friends = tweet["user"]["friends_count"] user_statuses = tweet["user"]["statuses_count"] user_created = tweet["user"]["created_at"] user_lang = tweet["user"]["lang"] coordinates = tweet ["coordinates"] place = tweet ["place"] rt_count = tweet ["retweet_count"] fav_count = tweet ["favorite_count"] hashtags = [] for hashtag in tweet ["entities"]["hashtags"]: hashtags.append(hashtag["text"]) urls = [] for url in tweet ["entities"]["urls"]: urls.append(url["expanded_url"]) c.execute ("INSERT INTO luck (timestamp, tweet_created_at, tweet_id, tweet_text, in_reply_status, in_reply_user_id, in_reply_screen_name, user_id, user_screen_name, user_location, user_url, user_description, user_followers_count, user_friends_count, users_statuses_count, user_created_at, user_lang, tweet_coords, tweet_place, tweet_retweet_count, tweet_fav_count, hashtags, urls) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", ((time.time()), created_at, identity, text, status_reply, user_reply, screen_name_reply, user_id, user_screen_name, user_location, user_url, user_description, user_followers, user_friends, user_statuses, user_created, user_lang, coordinates, place, rt_count, fav_count, str(hashtags), str(urls))) conn.commit () print (text) return True except BaseException, e: print "failed on data", str(e) time.sleep(5) def on_error (self, status): print status auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=["#מזל_טוב"]) 

Источник

Читайте также:  Python generator function iterator

Python-сообщество

[RSS Feed]

  • Начало
  • » Python для новичков
  • » Самое начало hello, world

#1 Дек. 22, 2015 18:51:29

Самое начало hello, world

Установил Python 2.7.11. Запустил IDLE, создал New file.

x=1 if x>0: print("Привет, Земляне!") 

В меню нажимаю RUN–> Run module F5–> появляется окно “source must be saved. OK to save”–> нажимаю OK. Ничего не происходит

x=1 if x>0: print("Hello, world!") 

То программа выводит Hello, world!

У меня два вопроса:
1. Что с кириллицей не так?
2. Почему “Run module F5” не запускается кнопкой F5? P.S. windows 10

#2 Дек. 22, 2015 19:08:15

Самое начало hello, world

Может, сначала объявить файл в кодировке UTF-8?

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#3 Дек. 22, 2015 19:47:38

Самое начало hello, world

#!/usr/bin/env python # -*- coding: UTF-8 -*- x=1 if x>0: print("ЫЫЫЫ!") 

1. Выводит см. вложенный файл. Далеко не “ЫЫЫЫ!”. А вот “windows-1251” помогло
2. Как быть с F5?
3.

#!/usr/bin/env python # -*- coding: UTF-8 -*- 

Поясните, в каких случаях ставится вначале ‘#’?
Почему в первой строчке после ‘#’ ставится ‘!’?
Что означает этот путь ‘/usr/bin/env python’?

Отредактировано Ejik87 (Дек. 22, 2015 19:47:57)

attachment

Прикреплённый файлы:
Screenshot_2.jpg (25,3 KБ)

#4 Дек. 22, 2015 22:34:16

Самое начало hello, world

Ejik87
Поясните, в каких случаях ставится вначале ‘#’?
Почему в первой строчке после ‘#’ ставится ‘!’?
Что означает этот путь ‘/usr/bin/env python’?

Извиняюсь, сам ооочень небольшой специалист, но… # — комментарии, если после нее ставится !- это документирование функций, вероятно так интерпретатору дается понять о кодировке файла , третье- это путь к директории $PATH для Пайтон. тут инфо. Вероятно так.

#5 Дек. 22, 2015 23:03:05

JOHN_16 От: Россия, Петропавловск-Камчатск Зарегистрирован: 2010-03-22 Сообщения: 3292 Репутация: 221 Профиль Отправить e-mail

Самое начало hello, world

Alex2000
не правильно

Если в начале текстового файла присутствует символы #! это означает для командной оболочки операционной системы что этот файл на исполнение запускается программой(интерпретатором) указанным далее. Таким образом строчка #!/usr/bin/env python говорит о том что данный текстовой файл следует запускать через программу /usr/bin/env и передать ей параметр python, в реальности эта UNIX команда вернет интерпретатор python который прописан в системном окружении ОС. Для Windows это работать не будет, так как в этом вопросе эти семейства ОС устроены по разному.
строчка # -*- coding: utf-8 -*- заданная в первых строчках файла указывает интерпретатору питона что данный python файл следует читать как файл с указанной кодировкой.

_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com

#6 Дек. 22, 2015 23:04:49

JOHN_16 От: Россия, Петропавловск-Камчатск Зарегистрирован: 2010-03-22 Сообщения: 3292 Репутация: 221 Профиль Отправить e-mail

Читайте также:  Php check ini file

Самое начало hello, world

Ejik87
Ваши вопросы,как обычно, сто пятсот милионов раз решалось и обсуждалось. Читайте книги. думайте, и не спешите по каждому вопросу писать на форум. он не для этого. Обучаться надо по книгам. благо они есть.

_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com

#7 Дек. 23, 2015 01:25:54

Самое начало hello, world

JOHN_16
Ejik87Ваши вопросы,как обычно, сто пятсот милионов раз решалось и обсуждалось. Читайте книги. думайте, и не спешите по каждому вопросу писать на форум. он не для этого. Обучаться надо по книгам. благо они есть.

Я понимаю, просто мне все не нужно. Мне нужны определенные основы для написания парсера сайта. Т.е. научиться пользоваться модулем requests(или аналогом) и основам кода. Я спрашивал в соседней ветке рекомендации обучающих ресурсов, но там не ответили.

Отредактировано Ejik87 (Дек. 23, 2015 01:26:28)

Источник

Русские Блоги

Маленький белый питон сложно | Источник Должен быть сохранен ОК, чтобы сохранить?

1. Произошла ошибка: Python всегда показываетSource Must be saved OK to save?, Невозможно сохранить файл кода

responses = <> # Установите флажок, чтобы указать, продолжается ли расследование polling_active = True while polling_active: # Подскажите, чтобы ввести имя и ответ респондента name = raw_input("\nWhat is your name?") response = raw_input("Which moutain would you like to climb someday? ") # Храните лист ответов в словаре responses[name] = response # Смотрите, если кто-то еще хочет участвовать в опросе repeat = raw_input("Would you like to let another person respon? (yes/ no)") if repeat == 'no': polling_active = False # Результаты опроса, отображать результаты print("\n--- Poll Results ---") for name, response in responses.items(): print(name + "would like to climb " + response + ".") 

2. Решение: это потому, что код содержит китайский язык, поэтому добавьте ** # coding = gbk ** в начале кода или_coding: utf-8 _ к

#coding=gbk responses = <> # Установите флажок, чтобы указать, продолжается ли расследование polling_active = True while polling_active: # Подскажите, чтобы ввести имя и ответ респондента name = raw_input("\nWhat is your name?") response = raw_input("Which moutain would you like to climb someday? ") # Храните лист ответов в словаре responses[name] = response # Смотрите, если кто-то еще хочет участвовать в опросе repeat = raw_input("Would you like to let another person respon? (yes/ no)") if repeat == 'no': polling_active = False # Результаты опроса, отображать результаты print("\n--- Poll Results ---") for name, response in responses.items(): print(name + "would like to climb " + response + ".") 

Источник

The IDLE editor in Python will not run my code when I do not save it

enter image description here

I have written code in a New file window in IDLE. When I run the code there is no output. Instead a dialog box appears showing a window accessing Python Folder 37-32. When i closed the dialog box and the file I tried to create a new simple code below but I when I ran the code I got the same Dialog box. What is wrong?

Читайте также:  Css label and checkbox

I have attached a screenshot showing the code and the dialog box that appears when the Module is run

2 Answers 2

Before you can execute your code, your first need to save the file. Thats the dialog box that popped up.

Thanks Lads, I saved the file in the Scripts folder. I named it «practice». I then tried to open it by using open(‘practice’) but i get an error saying no such file or directory. why is this?

IDLE is just a text editor. It can’t execute any code on it’s own. It first needs to save the file. That is where the dialog box is for. Then you can execute your code with IDLE’s run function. It basically says to python, hey, please run this code. So run the exact code as you made in the question. Than IDLE will say to Python to execute your code. In the same folder where the file is saved, a new file should pop up with the name hello.txt, as you coded yourself.

Ok, Im after opening the file named practice and I changed its code to to this open(‘new’,’w+’). I then selected run. I got this answer RESTART: C:\Users\Me\AppData\Local\Programs\Python\Python37-32\Scripts\practice.py. I checked in the Scripts folder and no file named «new» has been created. why is this?

You should have seen a popup box like below. Did you? Is is unclear?

Save Before Run or Check ? Source Must Be Saved OK to Save? [OK] [Cancel] 

One reason to require saving is that exception tracebacks refer to the file and line of lines that lead to the exception.

If you had saved, sum = 2+3 print(sum) would be a SyntaxError.

You can run single statements in Shell without saving.

The RESTART lines says that the shell re-initialized the environment for executing your code.

You should normally not save your code buried in the installation Scripts directory. Better to make a directory in your user directory, for instance, C:/Users/yourname/py/.

Yes, one should usually open a new question for unrelated questions. But without access to your machine, it is hard to know what happened with ‘new’. It may be that IDLE could create a file under . /appdate/. /Scripts/ , but your code cannot. If the open call did not raise and exception, it was likely created somewhere. Until you are more experienced, better to use absolute paths, such as C:/Users/yourname/py/new.txt .

Источник

Оцените статью