Re: pandas split and melt()
Update.
Option 1. - This annihilates all text in the column leaving nothing.
completed_tasks['Consultant'] =
completed_tasks['Consultant'].str.rstrip('.#123')
Option 2. - returns unhashable series list.
output =
completed_tasks[completed_tasks['Consultant']].str.contains(r'/\b[^\d\W]+\b/g')
neither option works as the column is a list.
Thanks
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Pytest share fixture data across the class methods
Hi,
I am using pytest to test my flask end points. I have grouped tests related to
all unauthenticated access in a class as you see below:
@pytest.mark.usefixtures("client_class")
class TestUnauthorizedRecipesAcces:
def test_update_a_recipe(self, create_recipe_record):
recipe = create_recipe_record(
{
"cook": "9 min",
"inactive": "20 min",
"level": "Easy",
"prep": "5 min",
"title": "Grilled Salmon I",
"total": "34 min",
"yields": "6 servings",
}
)
assert (
self.client.put(
url_for("recipes.recipes_api", _method="PUT", id=recipe.id),
json={"inactive": "10 min", "level": "easy"},
).status_code
== 401
)
def test_delete_a_recipe(self, create_recipe_record):
recipe = create_recipe_record(
{
"cook": "9 min",
"inactive": "20 min",
"level": "Easy",
"prep": "5 min",
"title": "Grilled Salmon I",
"total": "34 min",
"yields": "6 servings",
}
)
assert (
self.client.delete(
url_for("recipes.recipes_api", _method="DELETE", id=recipe.id)
).status_code
== 401
)
def test_fetch_a_recipe(self, create_recipe_record):
recipe = create_recipe_record(
{
"cook": "9 min",
"inactive": "20 min",
"level": "Easy",
"prep": "5 min",
"title": "Grilled Salmon I",
"total": "34 min",
"yields": "6 servings",
}
)
assert (
self.client.get(
url_for("recipes.recipes_api", _method="GET", id=recipe.id)
).status_code
== 401
)
def test_attach_a_category_to_a_recipe(
self, create_recipe_record, create_category_record
):
recipe = create_recipe_record(
{
"cook": "45 min",
"inactive": "",
"level": "",
"prep": "30 min",
"title": "Grilled Salmon II",
"total": "1 hr 15 min",
"yields": "4 servings",
}
)
category = create_category_record({"title": "Grilled Chicken"})
assert (
self.client.post(
url_for(
"recipe_categories.recipe_categories_api",
_method="POST",
recipe_id=recipe.id,
),
json={"id": category.id},
).status_code
== 401
)
def test_remove_a_category_from_a_recipe(
self, create_recipe_record, create_category_record
):
recipe = create_recipe_record(
{
"cook": "45 min",
"inactive": "",
"level": "",
"prep": "30 min",
"title": "Grilled Salmon II",
"total": "1 hr 15 min",
"yields": "4 servings",
}
)
category = create_category_record({"title": "Grilled Chicken"})
recipe.add_category(category.id)
assert (
self.client.delete(
url_for(
"recipe_categories.recipe_categories_api",
_method="DELETE",
recipe_id=recipe.id,
id=category.id,
)
).status_code
== 401
)
Those test data I created to build urls, other than that there are no used of
category, recipe records in this group. I was wondering if pytest can help to
share the data across all the methods instead of creating them everytime in
each method as I did above. Can you suggest me some tricks? I am looking for
something like:
@pytest.mark.usefixtures("client_class")
class TestUnauthorizedRecipesAcces:
#
def test_remove_a_category_from_a_recipe(self):
assert (
self.client.delete(
url_for(
"recipe_categories.recipe_categories_api",
_method="DELETE",
recipe_id=self.recipe.id,
id=self.category.id,
)
).status_code
== 401
)
How can I achieve this. Fixtures create_recipe_record, create_category_record
are created in contest.py file as a function scope
(https://gitlab.com/aruprakshit/flask_awesome_recipes/blob/master/tests/conftest.py)
. The tests can be seen here
https://gitlab.com/aruprakshit/flask_awesome_recipes/blob/master/tests/test_recipes.py#L253
.
Please give me some directions.
Thanks,
Arup Rakshit
[email protected]
--
https://mail.python.org/mailman/listinfo/py
Re: pandas split and melt()
Sayth Renshaw wrote:
> Hi
>
> Having fun with pandas filtering a work excel file.
> My current script opens selected and filters the data and saves as excel.
>
> import pandas as pd
> import numpy as np
>
> log = pd.read_excel("log_dump_py.xlsx")
> df = log.filter(items=['Completed', 'Priority', 'Session date',
> 'Consultant', 'Coach',
>'Delivery Method', 'Focus of Coaching', 'Leader', 'Site',
>'Coaching Description','Motor/Property',
>],)
> completed_tasks = df.loc[(df['Completed'] == 'Yes') &
> (df['Motor/Property'] == 'Motor') & (df['Delivery Method'] == 'Group
> Coaching')] print(completed_tasks.head(n=5))
> completed_tasks.to_excel("filtered_logs.xlsx")
>
> This leaves me with a set of several columns. The main column of concern
> for this example is a consultant
>
> Session date Consultant
> 2019-06-21 11:15:00 WNEWSKI, Joan;#17226;#BALIN,
Jock;#18139;#DUNE,
> Colem;#17230;
>
> How can I split the consultant column, keep only names and drop the
> numbers and for every session date create a line with data and consultants
> name?
>
> NB. There are varied amounts of consultants so splitting across columns is
> uneven. if it was even melt seems like it would be good
> https://dfrieds.com/data-analysis/melt-unpivot-python-pandas
>
>
> Thanks
>
> Sayth
Since I didn't find a cool shortcut I decided to use brute force:
$ cat pandas_explode_column.py
import pandas as pd
df = pd.DataFrame(
[
[
"2019-06-21 11:15:00",
"WNEWSKI, Joan;#17226;#BALIN, Jock;#18139;#DUNE, Colem;#17230;"
],
[
"2019-06-22 10:00:00", "Doe, John;#42;Robbins, Rita;"
]
],
columns=["Session date", "Consultant"]
)
def explode_consultants(consultants):
consultants = (c.lstrip("#") for c in consultants.split(";"))
return (c for c in consultants if c.strip("0123456789"))
def explode_column(df, column, split):
for _index, row in df.iterrows():
for part in split(row[column]):
yield [part if c == column else row[c] for c in df.columns]
def explode(df, column, split):
return pd.DataFrame(
explode_column(df, "Consultant", split), columns=df.columns
)
df2 = explode(df, "Consultant", explode_consultants)
print(df)
print(df2)
$ python3 pandas_explode_column.py
Session date Consultant
0 2019-06-21 11:15:00 WNEWSKI, Joan;#17226;#BALIN, Jock;#18139;#DUNE...
1 2019-06-22 10:00:00 Doe, John;#42;Robbins, Rita;
[2 rows x 2 columns]
Session date Consultant
0 2019-06-21 11:15:00 WNEWSKI, Joan
1 2019-06-21 11:15:00BALIN, Jock
2 2019-06-21 11:15:00DUNE, Colem
3 2019-06-22 10:00:00 Doe, John
4 2019-06-22 10:00:00 Robbins, Rita
[5 rows x 2 columns]
$
--
https://mail.python.org/mailman/listinfo/python-list
EuroPython 2019: Mobile Conference App available
We are pleased to announce the mobile conference app for EuroPython 2019, again hosted on the Attendify platform: EuroPython 2019 Conference App * https://ep2019.europython.eu/events/conference-app/ * Engage with the conference and its attendees The mobile app gives you access to the conference schedule (even offline), helps you in planing your conference experience (create your personal schedule with reminders) and provides a rich social engagement platform for all attendees. You can create a profile within the app or link this to your existing social accounts, share messages and photos, and easily reach out to other fellow attendees - all from within the app. Vital for all EuroPython 2019 attendees --- We will again use the conference app to keep you updated by sending updates of the schedule and inform you of important announcements via push notifications, so please consider downloading it. Many useful features Please see our EuroPython 2019 Conference App page for more details on features and guides on how to use them. https://ep2019.europython.eu/events/conference-app/ Don’t forget to get your EuroPython ticket -- If you want to join the EuroPython fun, be sure to get your tickets as soon as possible. https://ep2019.europython.eu/registration/buy-tickets/ Dates and Venues EuroPython will be held from July 8-14 2019 in Basel, Switzerland, at the Congress Center Basel (CCB) for the main conference days (Wed-Fri) and the FHNW Muttenz for the workshops/trainings/sprints days (Mon-Tue, Sat-Sun). The schedule is available at: https://ep2019.europython.eu/events/schedule/ Tickets can be purchased on our registration page: https://ep2019.europython.eu/registration/buy-tickets/ For more details, please have a look at our website and the FAQ: https://ep2019.europython.eu/faq Help spread the word Please help us spread this message by sharing it on your social networks as widely as possible. Thank you ! Link to the blog post: https://blog.europython.eu/post/185858710877/europython-2019-mobile-conference-app-available Tweet: https://twitter.com/europython/status/1143796573702434817 Enjoy, -- EuroPython 2019 Team https://ep2019.europython.eu/ https://www.europython-society.org/ -- https://mail.python.org/mailman/listinfo/python-list
File not able to link from drive
I am running a code to connect the google drive with google colab.But I have a
issue after connection.My Files are not able to read by google colab even after
link is established .
I have to read files from google drive in Google colab
My Code
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
I am also try this but still no results..
from google.colab import drive
drive.mount('/content/drive')
--
https://mail.python.org/mailman/listinfo/python-list
Re: pandas split and melt()
>
> Since I didn't find a cool shortcut I decided to use brute force:
>
> $ cat pandas_explode_column.py
> import pandas as pd
>
> df = pd.DataFrame(
> [
> [
> "2019-06-21 11:15:00",
> "WNEWSKI, Joan;#17226;#BALIN, Jock;#18139;#DUNE, Colem;#17230;"
> ],
> [
> "2019-06-22 10:00:00", "Doe, John;#42;Robbins, Rita;"
> ]
> ],
> columns=["Session date", "Consultant"]
> )
>
> def explode_consultants(consultants):
> consultants = (c.lstrip("#") for c in consultants.split(";"))
> return (c for c in consultants if c.strip("0123456789"))
>
> def explode_column(df, column, split):
> for _index, row in df.iterrows():
> for part in split(row[column]):
> yield [part if c == column else row[c] for c in df.columns]
>
> def explode(df, column, split):
> return pd.DataFrame(
> explode_column(df, "Consultant", split), columns=df.columns
> )
>
> df2 = explode(df, "Consultant", explode_consultants)
>
> print(df)
> print(df2)
> $ python3 pandas_explode_column.py
> Session date Consultant
> 0 2019-06-21 11:15:00 WNEWSKI, Joan;#17226;#BALIN, Jock;#18139;#DUNE...
> 1 2019-06-22 10:00:00 Doe, John;#42;Robbins, Rita;
>
> [2 rows x 2 columns]
> Session date Consultant
> 0 2019-06-21 11:15:00 WNEWSKI, Joan
> 1 2019-06-21 11:15:00BALIN, Jock
> 2 2019-06-21 11:15:00DUNE, Colem
> 3 2019-06-22 10:00:00 Doe, John
> 4 2019-06-22 10:00:00 Robbins, Rita
>
> [5 rows x 2 columns]
> $
Mind a little blown :-). Going to have to play and break this several times to
fully get it.
Thanks
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: pandas split and melt()
Sayth Renshaw wrote:
> Peter Otten wrote:
>> def explode_consultants(consultants):
Should have called that split_consultants(); takes a string and
>> consultants = (c.lstrip("#") for c in consultants.split(";"))
splits by ";", removes leading "#"
>> return (c for c in consultants if c.strip("0123456789"))
filters out the digit-only values.
>> def explode_column(df, column, split):
>> for _index, row in df.iterrows():
iterates over the rows of the data frame
>> for part in split(row[column]):
iterates over the names extracted by explode_consultants() from the
"Consultants" field
>> yield [part if c == column else row[c] for c in df.columns]
Makes one row per consultant, replacing the contents of the Consultants
column with the current consultant (bound to the part variable, e. g. with
part = "Doe, John"
yield [
"Doe, John" if c == "Consultants" else row[c]
for c in ["Session Date", "Consultants"]
]
>> def explode(df, column, split):
Make a new data frame from the rows generated by explode_column(), reusing
the column names from the original data frame.
>> return pd.DataFrame(
>> explode_column(df, "Consultant", split), columns=df.columns
Here's a bug -- "Consultant" is hardcoded, but the column argument should be
instead.
>> )
>> df2 = explode(df, "Consultant", explode_consultants)
>>
>> print(df)
>> print(df2)
>> $ python3 pandas_explode_column.py
>> Session date Consultant
>> 0 2019-06-21 11:15:00 WNEWSKI, Joan;#17226;#BALIN, Jock;#18139;#DUNE...
>> 1 2019-06-22 10:00:00 Doe, John;#42;Robbins, Rita;
>>
>> [2 rows x 2 columns]
>> Session date Consultant
>> 0 2019-06-21 11:15:00 WNEWSKI, Joan
>> 1 2019-06-21 11:15:00BALIN, Jock
>> 2 2019-06-21 11:15:00DUNE, Colem
>> 3 2019-06-22 10:00:00 Doe, John
>> 4 2019-06-22 10:00:00 Robbins, Rita
>>
>> [5 rows x 2 columns]
>> $
>
> Mind a little blown :-). Going to have to play and break this several
> times to fully get it.
Here's another usage example for explode() which "explodes" the "ham" column
using range():
>>> df3 = pd.DataFrame([[2, "foo"], [3, "bar"], [0, "baz"]], columns=["ham",
"spam"])
>>> explode(df3, "ham", range)
ham spam
00 foo
11 foo
20 bar
31 bar
42 bar
[5 rows x 2 columns]
--
https://mail.python.org/mailman/listinfo/python-list
Copying a row from a range of Excel files to another
I was asked to copy a certain line from about 300 Excel lines to a new
Excel file. That is not something I would like to do by hand and I
immediately thought: that should be possible with Python.
And it is. I was surprised how fast I could write that with openpyxl.
My first try was not very neat, but a proof of concept. Then by
looking better at the possibilities I could get much cleaner code. But
I am still not completely happy. At the moment I have the following
code:
wb_out = Workbook()
for filepath in filepathArr:
current_row = []
wb_in = load_workbook(filepath)
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_in.close()
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + report_end)
wb_out.close()
I could not find a way to copy a row from one workbook to another.
That is why I put the row in current_row and do an append. Am I
overlooking something, or is that really the way to do this?
I am not used to writing GUI programs. (I have to learn tkinter also.)
What is the best way to handle potential errors? It could go wrong on
line 1, 4, 5, 7, 8, 9 and 10. Should I catch every exception alone, or
all together, or something in between?
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
--
https://mail.python.org/mailman/listinfo/python-list
Creating a Windows executable on a Linux system
I need to write a Python desktop program. I create it on a Linux system, but it has to run on a Windows system. When looking at how to create an executable it seems that you need to be on a Windows system to create a Windows executable. Is this true, or is it possible to create a Windows executable on a Linux system? Any pointers about best practice creating a standalone executable are welcome. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
Make sure the window title is visible in tkinter
I need to write a desktop program. I choose to use tkinter. How can I
make sure the window title is visible? For example when I have the
following code:
from tkinter import Button, filedialog, Label, messagebox, Tk
window = Tk()
window.title('A long window title')
Button (window, text = 'Short text').pack()
window.mainloop()
I see only a part of the 'A', but I would like to see the complete:
'A long window title'
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
--
https://mail.python.org/mailman/listinfo/python-list
What type of error is it
I am writing a GUI program with tkinter. One function I have is: def select_dir(): try: directory = filedialog.askdirectory() if directory == '': messagebox.showinfo(info_str, canceled_report) return chdir(directory) filepathArr = sorted(glob(regex)) if len(filepathArr) == 0: messagebox.showwarning(warning_str, nofiles_str) return generate_report(filepathArr) except: messagebox.showerror(error_str, error_select_str) raise I use the raise to see what the exception was. That works, because tkinter takes over again. This works for me when I run it from the command-line, but it has to become a stand-alone executable. Is there a way to find out what the cause of the exception was, so I can put it in the error message? -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
Re: What type of error is it
Cecil Westerhof writes: > I am writing a GUI program with tkinter. One function I have is: > def select_dir(): > try: > directory = filedialog.askdirectory() > if directory == '': > messagebox.showinfo(info_str, canceled_report) > return > chdir(directory) > filepathArr = sorted(glob(regex)) > if len(filepathArr) == 0: > messagebox.showwarning(warning_str, nofiles_str) > return > generate_report(filepathArr) > except: >messagebox.showerror(error_str, error_select_str) >raise > > I use the raise to see what the exception was. That works, because > tkinter takes over again. > This works for me when I run it from the command-line, but it has to > become a stand-alone executable. Is there a way to find out what the > cause of the exception was, so I can put it in the error message? Found it. I just need to change the last three lines to: except Exception as err: messagebox.showerror(error_str, error_select_str + '\n\n\n\n' + str(err)) -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
Re: Creating a Windows executable on a Linux system
Cecil Westerhof wrote: >I need to write a Python desktop program. I create it on a Linux >system, but it has to run on a Windows system. When looking at how to >create an executable it seems that you need to be on a Windows system >to create a Windows executable. Is this true, or is it possible to >create a Windows executable on a Linux system? >Any pointers about best practice creating a standalone executable are >welcome. Is using a portable Python installation an option? -- Dipl.-Inform(FH) Peter Heitzer, [email protected] -- https://mail.python.org/mailman/listinfo/python-list
Re: Copying a row from a range of Excel files to another
Cecil Westerhof writes:
> I was asked to copy a certain line from about 300 Excel lines to a new
> Excel file. That is not something I would like to do by hand and I
> immediately thought: that should be possible with Python.
>
> And it is. I was surprised how fast I could write that with openpyxl.
> My first try was not very neat, but a proof of concept. Then by
> looking better at the possibilities I could get much cleaner code. But
> I am still not completely happy. At the moment I have the following
> code:
> wb_out = Workbook()
> for filepath in filepathArr:
> current_row = []
> wb_in = load_workbook(filepath)
> for cell in wb_in.active[src_row]:
> current_row.append(cell.value)
> wb_out.active.append(current_row)
> wb_in.close()
> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
> report_end)
> wb_out.close()
>
> I could not find a way to copy a row from one workbook to another.
> That is why I put the row in current_row and do an append. Am I
> overlooking something, or is that really the way to do this?
>
>
> I am not used to writing GUI programs. (I have to learn tkinter also.)
> What is the best way to handle potential errors? It could go wrong on
> line 1, 4, 5, 7, 8, 9 and 10. Should I catch every exception alone, or
> all together, or something in between?
I rewrote it like:
wb_in = None
wb_out = None
try:
wb_out = Workbook()
for filepath in filepathArr:
current_row = []
wb_in = load_workbook(filepath)
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_in.close()
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
report_end)
wb_out.close()
messagebox.showinfo(info_str, created_report)
except Exception as err:
if wb_in:
wb_in.close()
if wb_out:
wb_close
messagebox.showerror(error_str,
error_generate + '\n\n\n\n' + str(err))
Is it necessary to close the workbooks to circumvent a resource leak?
Is it a problem when a workbook is closed two times? If so I need to
make sure that this is not possible.
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
--
https://mail.python.org/mailman/listinfo/python-list
Re: Make sure the window title is visible in tkinter
On Wed, 26 Jun 2019 13:25:15 +0200, Cecil Westerhof wrote:
> I need to write a desktop program. I choose to use tkinter. How can I
> make sure the window title is visible? For example when I have the
> following code:
> from tkinter import Button, filedialog, Label, messagebox, Tk
>
>
> window = Tk()
> window.title('A long window title')
> Button (window, text = 'Short text').pack()
> window.mainloop()
>
> I see only a part of the 'A', but I would like to see the complete:
> 'A long window title'
According to link below, it is not possible...
"Tkinter has no way of knowing how long the title is on the titlebar."
https://stackoverflow.com/questions/35273690/tkinter-window-not-wide-enough-to-display-window-title
--
GNU/Linux user #557453
"There are only 10 types of people in the world...
those who understand Binary and those who don't."
-Spike
--
https://mail.python.org/mailman/listinfo/python-list
Re: Creating a Windows executable on a Linux system
"Peter Heitzer" writes: > Cecil Westerhof wrote: >>I need to write a Python desktop program. I create it on a Linux >>system, but it has to run on a Windows system. When looking at how to >>create an executable it seems that you need to be on a Windows system >>to create a Windows executable. Is this true, or is it possible to >>create a Windows executable on a Linux system? > >>Any pointers about best practice creating a standalone executable are >>welcome. > Is using a portable Python installation an option? That is not supported anymore. But they pointed to WinPython. I will look into that/ One important thing is that the application uses openpyxl and tkinter. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
Re: Copying a row from a range of Excel files to another
Cecil Westerhof writes: > Is it necessary to close the workbooks to circumvent a resource > leak? Still like to know. When not necessary it is better not to cloes them I think. > Is it a problem when a workbook is closed two times? If so I need to > make sure that this is not possible. That is not a problem. I tried it and it just works. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
Re: Make sure the window title is visible in tkinter
Wildman writes:
> On Wed, 26 Jun 2019 13:25:15 +0200, Cecil Westerhof wrote:
>
>> I need to write a desktop program. I choose to use tkinter. How can I
>> make sure the window title is visible? For example when I have the
>> following code:
>> from tkinter import Button, filedialog, Label, messagebox, Tk
>>
>>
>> window = Tk()
>> window.title('A long window title')
>> Button (window, text = 'Short text').pack()
>> window.mainloop()
>>
>> I see only a part of the 'A', but I would like to see the complete:
>> 'A long window title'
>
> According to link below, it is not possible...
> "Tkinter has no way of knowing how long the title is on the titlebar."
>
> https://stackoverflow.com/questions/35273690/tkinter-window-not-wide-enough-to-display-window-title
OK, then I will have to live with it.
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
--
https://mail.python.org/mailman/listinfo/python-list
Re: Make sure the window title is visible in tkinter
Cecil Westerhof wrote:
> I need to write a desktop program. I choose to use tkinter.
>
> How can I make sure the window title is visible? For example
> when I have the following code :
> from tkinter import Button, filedialog, Label, messagebox, Tk
>
>
> window = Tk()
> window.title('A long window title')
> Button (window, text = 'Short text').pack()
> window.mainloop()
>
> I see only a part of the 'A', but I would like to see
> the complete :
>
> 'A long window title'
>
You might try setting a given window geometry
to accomodate the long title
win_w = 400
win_h = 300
ofs_h = 40
ofs_v = 30
window.geometry( "%dx%d+%d+%d" % ( win_w , win_h , ofs_h , ofs_v ) )
Maybe add a bit of extra space for users
with different default font sizes
Not a general solution
but perhaps workable
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
--
https://mail.python.org/mailman/listinfo/python-list
Re: Creating a Windows executable on a Linux system
On 2019-06-26, Cecil Westerhof wrote: > [...] it seems that you need to be on a Windows system to create a > Windows executable. Is this true, or is it possible to create a > Windows executable on a Linux system? AFIAK, you have to use a Windows system to create a windows executable. In the past, I used py2exe+InnoSetup for both tkinter and wxPython Windows apps. But, py2exe seems to be a dead project and the last time I tried to use it (a couple years ago) I couldn't get it to work on recent Windows+Python versions. Currently I use cx_freeze+InnoSetup for tkinter apps. (I no longer have any wxPython apps I maintain for Windows.) Another popular option is PyInstaller, but I've never tried it. http://www.py2exe.org/ https://anthony-tuininga.github.io/cx_Freeze/ https://www.pyinstaller.org/ http://www.jrsoftware.org/isinfo.php -- Grant Edwards grant.b.edwardsYow! I wonder if I should at put myself in ESCROW!! gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Make sure the window title is visible in tkinter
On 2019-06-26, Cousin Stanley wrote: > You might try setting a given window geometry > to accomodate the long title > [...] > window.geometry( "%dx%d+%d+%d" % ( win_w , win_h , ofs_h , ofs_v ) ) > Maybe add a bit of extra space for users with different default > font sizes IIRC, there is a way to get tkInter to render a string in a particular font so that you can then find out how wide the result is in pixels. It's been a long time since I needed to do that, and it was a bit of a hassle. I'm not sure how you would make sure it's rendered in the same font as the window title. -- Grant Edwards grant.b.edwardsYow! I'm a fuschia bowling at ball somewhere in Brittany gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Hiding a progressbar in tkinter
I just started with GUI stuff in tkinter. I have a progressbar, but I want it to be only visible when it is used. So I tried the following: window = Tk() window.title(window_str) frame = Frame(window) frame.pack(side = "top", fill = "both", expand = True) Button(window, text = button_str, command = select_dir).pack() progress = ttk.Progressbar(window, orient = "horizontal", length = 200, mode = "determinate") progress.pack() progress.lower(frame) window.mainloop() But that does not hide the progressbar. What am I doing wrong? I could use pack_forget, but that will change the dimensions of the window. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
Re: Creating a Windows executable on a Linux system
On Wed, 2019-06-26 at 13:41 +0200, Cecil Westerhof wrote: > I need to write a Python desktop program. I create it on a Linux > system, but it has to run on a Windows system. When looking at how to > create an executable it seems that you need to be on a Windows system > to create a Windows executable. Is this true, or is it possible to > create a Windows executable on a Linux system? > > Any pointers about best practice creating a standalone executable are > welcome. I'm no expert, but installing pyinstaller in wine works for me. I admit, though, that I have only tried it with one file, which I wanted to send to my brother. I'm using Ubuntu 18.04, and the command: wine ~/.wine/drive_c/Python34/Scripts/pyinstaller.exe --onefile bin/GradientProfile_v2.py produces a file that my brother can run on his Windows 10 machine. David -- https://mail.python.org/mailman/listinfo/python-list
Re: Make sure the window title is visible in tkinter
On Wed, 26 Jun 2019 15:05:15 +0200, Cecil Westerhof wrote: >> OK, then I will have to live with it. I did find some references to a method where you first disable the Tkinter title bar using overrideredirect(True). Then you create a new title bar using a frame and canvas. You can then set the font/size for the canvas. I think you could do it with a label but if you want an icon and close (X) button, that could be a problem. IFAIK you can have only one image on a label. -- GNU/Linux user #557453 "I am Lrrr! Ruler of the planet Omicron Persei 8! Can I crash on your couch?" -Lrrr -- https://mail.python.org/mailman/listinfo/python-list
Re: Hiding a progressbar in tkinter
On Wed, 26 Jun 2019 17:47:39 +0200, Cecil Westerhof wrote: > I just started with GUI stuff in tkinter. I have a progressbar, but I > want it to be only visible when it is used. So I tried the following: > window = Tk() > window.title(window_str) > frame = Frame(window) > frame.pack(side = "top", fill = "both", expand = True) > Button(window, text = button_str, command = select_dir).pack() > progress = ttk.Progressbar(window, orient = "horizontal", length = 200, >mode = "determinate") > progress.pack() > progress.lower(frame) > window.mainloop() > > But that does not hide the progressbar. What am I doing wrong? > > I could use pack_forget, but that will change the dimensions of the > window. Here is an example using grid_forget(). https://stackoverflow.com/questions/33768577/tkinter-gui-with-progress-bar Disclaimer: I have not tested this code and cannot say for certain that it will work the way you want. -- GNU/Linux user #557453 "Be vewy vewy qwiwet, I'm hunting wabbits." -Elmer Fudd -- https://mail.python.org/mailman/listinfo/python-list
Re: Hiding a progressbar in tkinter
On 2019-06-26 16:47, Cecil Westerhof wrote: I just started with GUI stuff in tkinter. I have a progressbar, but I want it to be only visible when it is used. So I tried the following: window = Tk() window.title(window_str) frame = Frame(window) frame.pack(side = "top", fill = "both", expand = True) Button(window, text = button_str, command = select_dir).pack() progress = ttk.Progressbar(window, orient = "horizontal", length = 200, mode = "determinate") progress.pack() progress.lower(frame) window.mainloop() But that does not hide the progressbar. What am I doing wrong? I could use pack_forget, but that will change the dimensions of the window. The progress bar isn't hidden because there's nothing on top of it to hide it. import tkinter as tk import tkinter.ttk as ttk window = tk.Tk() window.title(window_str) frame = tk.Frame(window) frame.pack(side='top', fill='both', expand=True) tk.Button(window, text=button_str, command=select_dir).pack() # Create a frame to hold the progress bar. progress_frame = tk.Frame(window) progress_frame.pack(fill='x', expand=True) # Put the progress bar into the progress frame, ensuring that it fills the grid cell. progress = ttk.Progressbar(progress_frame, orient='horizontal', length=200, mode='determinate') progress.grid(row=0, column=0, sticky='nsew') # Now put a blank frame into the progress frame over the progress bar, ensuring that it fills the same grid cell. blank = tk.Frame(progress_frame) blank.grid(row=0, column=0, sticky='nsew') # Raise the progress bar over the blank frame to reveal it. progress.tkraise() # Lower the progress bar underneath the blank frame to hide it. progress.lower() window.mainloop() -- https://mail.python.org/mailman/listinfo/python-list
Re: Copying a row from a range of Excel files to another
On 2019-06-26 13:15, Cecil Westerhof wrote:
Cecil Westerhof writes:
I was asked to copy a certain line from about 300 Excel lines to a new
Excel file. That is not something I would like to do by hand and I
immediately thought: that should be possible with Python.
And it is. I was surprised how fast I could write that with openpyxl.
My first try was not very neat, but a proof of concept. Then by
looking better at the possibilities I could get much cleaner code. But
I am still not completely happy. At the moment I have the following
code:
wb_out = Workbook()
for filepath in filepathArr:
current_row = []
wb_in = load_workbook(filepath)
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_in.close()
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + report_end)
wb_out.close()
I could not find a way to copy a row from one workbook to another.
That is why I put the row in current_row and do an append. Am I
overlooking something, or is that really the way to do this?
I am not used to writing GUI programs. (I have to learn tkinter also.)
What is the best way to handle potential errors? It could go wrong on
line 1, 4, 5, 7, 8, 9 and 10. Should I catch every exception alone, or
all together, or something in between?
I rewrote it like:
wb_in = None
wb_out = None
try:
wb_out = Workbook()
for filepath in filepathArr:
current_row = []
wb_in = load_workbook(filepath)
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_in.close()
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
report_end)
wb_out.close()
messagebox.showinfo(info_str, created_report)
except Exception as err:
if wb_in:
wb_in.close()
if wb_out:
Missing ():
wb_close
messagebox.showerror(error_str,
error_generate + '\n\n\n\n' + str(err))
Is it necessary to close the workbooks to circumvent a resource leak?
Is it a problem when a workbook is closed two times? If so I need to
make sure that this is not possible.
Does Workbook support the 'with' statement?
If it does, then that's the best way of doing it.
(Untested)
with Workbook() as wb_out:
for filepath in filepathArr:
current_row = []
with load_workbook(filepath) as wb_in:
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d')
+ report_end)
--
https://mail.python.org/mailman/listinfo/python-list
for line3 in myips matching too longer matches.
### CODE: elif line1.rstrip(‘\n’) in line2.strip(‘\n’): for line3 in myips: print “###” print “line1 is %s” % line1.rstrip(‘\n’) print “line2 is %s” % line2.strip(‘\n’) ### OUTPUT: line1 is 10.10.168.2 line2 is - address: 10.10.168.27 # myhost ### I think the problem is here: line1.rstrip(‘\n’) in line2.strip(‘\n’): I want it to match only 10.10.168.2 AND 10.10.168.2: NOT match 10.10.168.2[0-9] If someone out there knows a simple solution. I would love to see it. Thanks in advance. crzzy1 -- https://mail.python.org/mailman/listinfo/python-list
Re: Copying a row from a range of Excel files to another
MRAB writes:
> Does Workbook support the 'with' statement?
>
> If it does, then that's the best way of doing it.
>
> (Untested)
>
> with Workbook() as wb_out:
> for filepath in filepathArr:
> current_row = []
>
> with load_workbook(filepath) as wb_in:
> for cell in wb_in.active[src_row]:
> current_row.append(cell.value)
>
> wb_out.active.append(current_row)
>
> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
> report_end)
It seems not. I get AttributeError.
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
--
https://mail.python.org/mailman/listinfo/python-list
Re: for line3 in myips matching too longer matches.
On 26Jun2019 14:21, Chris Roberts wrote:
###
CODE:
elif line1.rstrip(‘\n’) in line2.strip(‘\n’):
for line3 in myips:
print “###”
print “line1 is %s” % line1.rstrip(‘\n’)
print “line2 is %s” % line2.strip(‘\n’)
###
OUTPUT:
line1 is 10.10.168.2
line2 is - address: 10.10.168.27 # myhost
###
I think the problem is here:
line1.rstrip(‘\n’) in line2.strip(‘\n’):
I want it to
match only 10.10.168.2 AND 10.10.168.2:
NOT match 10.10.168.2[0-9]
If someone out there knows a simple solution. I would love to see it.
Well the usual solution is to break line2 in to "words".
When you go:
'10.10.168.2' in ' - address: 10.10.168.27 # myhost'
you're testing a substring match. But if you go:
'10.10.168.2' in ['-', 'address:', '10.10.168.27', '#', 'myhost']
it does a membership test i.e. does the _exact string_ '10.10.168.2'
occur in this list of strings.
(This isn't magic, the "in" operator uses an object's __contains__
method (or falls back to iteration and comparison), so the nature of the
test is driven by the type of the object being tested (on the right, for
"in")).
So...
address = line1.rstrip('\n')
words = line2.split()
if address in words:
...
Personally I'd be being pickier about line1 as well, but ifyour input is
well defined that may not matter.
Cheers,
Cameron Simpson
--
https://mail.python.org/mailman/listinfo/python-list
Re: Copying a row from a range of Excel files to another
On 2019-06-26 22:14, Cecil Westerhof wrote:
MRAB writes:
Does Workbook support the 'with' statement?
If it does, then that's the best way of doing it.
(Untested)
with Workbook() as wb_out:
for filepath in filepathArr:
current_row = []
with load_workbook(filepath) as wb_in:
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
report_end)
It seems not. I get AttributeError.
You didn't say which line.
Anyway, if Workbooks are closed using a method called "close", you can
wrap them in a "closing" context manager:
from contextlib import closing
with closing(Workbook()) as wb_out:
for filepath in filepathArr:
current_row = []
with closing(load_workbook(filepath)) as wb_in:
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d')
+ report_end)
--
https://mail.python.org/mailman/listinfo/python-list
Re: for line3 in myips matching too longer matches.
Chris Roberts wrote:
> ###
> CODE:
>elif line1.rstrip(‘\n’) in line2.strip(‘\n’):
>for line3 in myips:
>print “###”
>print “line1 is %s” % line1.rstrip(‘\n’)
>print “line2 is %s” % line2.strip(‘\n’)
> ###
> OUTPUT:
> line1 is 10.10.168.2
> line2 is - address: 10.10.168.27 # myhost
> ###
>
> I think the problem is here:
> line1.rstrip(‘\n’) in line2.strip(‘\n’):
>
> I want it to
> match only 10.10.168.2 AND 10.10.168.2:
> NOT match 10.10.168.2[0-9]
>
> If someone out there knows a simple solution. I would love to see it.
> Thanks in advance.
> crzzy1
Not sure exactly what the input is but a comprehension would do this.
[x for x in input_line.split(' ') if == '10.10.168.2']
Cheers
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: Copying a row from a range of Excel files to another
Cecil Westerhof wrote:
> I was asked to copy a certain line from about 300 Excel lines to a new
> Excel file. That is not something I would like to do by hand and I
> immediately thought: that should be possible with Python.
>
> And it is. I was surprised how fast I could write that with openpyxl.
> My first try was not very neat, but a proof of concept. Then by
> looking better at the possibilities I could get much cleaner code. But
> I am still not completely happy. At the moment I have the following
> code:
> wb_out = Workbook()
> for filepath in filepathArr:
> current_row = []
> wb_in = load_workbook(filepath)
> for cell in wb_in.active[src_row]:
> current_row.append(cell.value)
> wb_out.active.append(current_row)
> wb_in.close()
> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
> report_end)
> wb_out.close()
>
> I could not find a way to copy a row from one workbook to another.
> That is why I put the row in current_row and do an append. Am I
> overlooking something, or is that really the way to do this?
>
>
>
> --
> Cecil Westerhof
Pandas may work out better.
import pandas as pd
df = pd.read_excel('spreadsheet')
# find the row by filtering with regex
df2 = df.'column'.str.contains('criteria as regex')
df2.pd.save_excel('output.xlsx')
Cheers
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
