Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread a a
On Monday, 13 March 2023 at 16:12:04 UTC+1, Thomas Passin wrote:
> On 3/13/2023 12:39 AM, a a wrote: 
> > But some unknown reasons Matplotlib and numpy crash my Python 3.8 for 
> > Windows , 32-bit and no support is offered
> It is possible, using pip, to downgrade versions (e.g., of Matplotlob 
> and numpy) to see if you can find versions that work. Of course moving 
> to 64-bit Python >= 3.10 would be better, but if that were possible I 
> imagine you would have done it already. 
> 
> BTW, it would be useful if you said what operating system you are using 
> (I've been assuming Windows).
sorry
Windows 7

My concept in building Earthquake Prediction System based on Precognition is
to use RTL Software Defined Radio (SDR) to receive data from outdoor seismic 
sensors (smartphones turned into seismographs - sending acceleration data via 
audio output, to be transmitted by radio transmitter to a remote RTL SDR 
station, for real time processing, P-wave energy envelope calculation, 
earthquake depth calculation sine in case of Turkey, USGS assigns 10km depth 
value by default to a single EQ event.

Why SDR ?
Since I don't expect Cellular network to work and be operational in remote, 
mountain regions of Turkey after the strong 7,8 earthquake, so SDR should work 
as backup for cellular 3G/LTE network in the region.

In case of Android smartphones I need to switch to Python for Android to get 
flexibility offered by scripting to support earthquake study ideas just in time 
and to share such ideas with friends.


---

python-for-android · PyPI
https://pypi.org/project/python-for-android

python-for-android is a packaging tool for Python apps on Android. You can 
create your own Python distribution including the modules and dependencies you 
want, and bundle it in an APK or AAB along with your own code. Features 
include: Different app backends including Kivy, PySDL2, and a WebView with Pyt… 
See more
Documentation

Follow the quickstartinstructionsto install and begin creating APKs and AABs. 
Quick instructions: install python-for-android with: (for the develop branch: 
pip install git+https://github.com/kivy/… See more
Contributing

We love pull requests and discussing novel ideas. Check out the Kivyproject 
contribution guideandfeel free to improve python-for-android. See ou… See more
Support

If you need assistance, you can ask for help on our mailing list: 1. User 
Group: https://groups.google.com/group/kivy-users 2. Email: 
kivy-us...@googlegroups.com … See more
History

In 2015 these tools were rewritten to provide a new, easier-to-use 
andeasier-to-extend interface. If you'd like to browse the old toolchain, 
itsstatus is re… See more
Explore further
Global web icon
Is there a way to run Python on Android? - Stack Overflow
stackoverflow.com
Global web icon
How to Download and Install Python for Android
mptricks.com
Global web icon
How to develop Android app completely using python?
stackoverflow.com
Global web icon
How to download and install Python Latest Version on An…
geeksforgeeks.org
Global web icon
An Introduction to Python for Android Development
pythonpool.com
Recommended to you based on what's popular • Feedback
From pypi.org
Content
Documentation
Support
Contributing
History
Create and run Python apps on your Android phone
https://opensource.com/article/20/8/python-android...

WebAug 26, 2020 · $ pkg install python Once the installation and auto set-up of 
configuration is complete, it’s time to build your application. Build an app 
for Android on Android Now that you have a terminal installed, you can …
GitHub - kivy/python-for-android: Turn your Python application …
https://github.com/kivy/python-for-android

Webpython-for-android is a packaging tool for Python apps on Android. You can 
create your own Python distribution including the modules and dependencies you 
want, and bundle it in an APK or AAB along with your …
When did Python 2 stop supporting Android?
See this and other topics on this result
An introduction to Python on Android - Android Authority
https://www.androidauthority.com/an-introduction...

WebMar 31, 2017 · Python is a particularly simple and elegant coding language 
that is designed with the beginner in mind. The problem is that learning to …

Reviews: 8

Estimated Reading Time: 9 mins

Android - Python Wiki
https://wiki.python.org/moin/Android

WebThere are several ways to use Python on Android. The following table 
summarizes those projects which are currently active: BeeWare is a toolkit for 
developing cross-platform …
People also ask
How to run Python on Android?Create and run Python apps on your Android phone 1 
Install Termux on Android. First, install the Termux application. ... 2 Build 
an app for Android on Android. Now that you have a terminal installed, you can 
work on your Android phone largely as if it were just another Linux computer. 3 
Write Python code on Android. You're all set up. ...
Create and run Python apps on your Android phone
opensource.c

Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread a a
On Monday, 13 March 2023 at 16:16:28 UTC+1, Thomas Passin wrote:
> On 3/13/2023 12:39 AM, a a wrote:
> > But what I need is analysis of seismograms from 4,000 seismographs world 
> > wide to detect P-wave energy distribution underground around the earthquake 
> > to verify EQ Domino Effect
> In that case, you will have to do a great deal of work to get all that 
> data into a common usable form, cleaned and errors removed. That will 
> be a lot of effort no matter what language you use. In the Matplotlib 
> lesson you pointed to, the work was already done, for one one earthquake 
> at one location. 
> 
> The reference I gave, 
> https://towardsdatascience.com/earthquake-time-series-forecasts-using-a-hybr 
> 
> id-clustering-lstm-approach-part-i-eda-6797b22aed8c 
> 
> actually includes a Python script that does this work for some selected 
> ranges of data, so it might be a good starting point.
Thank you
excellent example

"The imported json files were heavily-nested; hence, during data cleaning, I 
“denested” the json files, transformed them into dataframes, fixed the column 
datatypes, imputed the NaN values, and finally concatenated them into a global 
dataframe, which was workable. For a full description of data cleaning, visit 
my GitHub profile. Finally, I indexed the dataframe by timestamps as a 
time-series dataframe:

https://towardsdatascience.com/earthquake-time-series-forecasts-using-a-hybrid-clustering-lstm-approach-part-i-eda-6797b22aed8c


I would like to work with Saied Mighani one day but unfortunately, seismology 
projects, studies are one-man activity.

I am success oriented in building Earthquake Prediction System
and I am sure, P-wave energy envelope calculate for every earthquake, for every 
seismographic station can give valuable hints on how earthquake energy is 
distributed underground, since what is recorded by surface seismographs is some 
form of such P-wave envelope energy transferred at the direction of surface 
placed seismograph.

Ideas are great but life is for real ;)

thank you
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread avi.e.gross
Hi,

This seems again to be a topic wandering. Was the original question whether
Python could be used for dealing with Seismic data of some unspecified sort
as in PROCESSING it and now we are debating how to clean various aspects of
data and make things like data.frames and extract subsets for analysis?

Plenty of the above can be done in any number of places ranging from
languages like Python and R to databases and SQL. If the result you want to
analyze can then be written in a format with rows and columns containing the
usual suspects like numbers and text and dates and so on, then this part of
the job can be done anywhere you want.

And when you have assembled your data and now want to make a query to
generate a subset such as data in a date range that is from a set of
measuring stations and with other qualities, then you can simply save the
data to a file in whatever format, often something like a .CSV.

It is the following steps where you want to choose your language based on
what is available. Are you using features like a time series, for example?
Are you looking or periodicity. Is graphing a major aspect and do you need
some obscure graph types not easily found but that are parts of
packages/modules in some language like R or Python? Do you need the analysis
to have interactive aspects such as from a GUI, or a web page? Does any
aspect of your work include things like statistical analyses or machine
learning? The list goes on.

As mentioned, people who do lots of stuff along these lines can share some
tools in python, or elsewhere, they find useful and that might help fit the
needs of the OP but they work best when they have a better idea of what
exactly you want to do. Part of what I gleaned, was a want to do a 3-D graph
that rotates. Python has multiple graphics packages and so on as do
languages like R. The likelihood of finding something useful goes up if you
identify if there are communities of people doing similar work and can share
some of their tools. 

Hence the idea of focused searches. Asking here will largely get you people
mainly who use Python and if it turns out R or something entirely else meets
your needs better, perhaps Mathematica  even if you have to pay for it if
that is expected by your peers.

My guess is that python would be a decent choice as it can do almost
anything, but for practical purposes, you do not want to stick with what is
in the base and probably want to use extensions like numpy/pandas and
perhaps others like scipy and if doing graphics, there are too many
including matplotlib and seaborn but you may need something specialized for
your needs.

I cannot stress the importance of making sure the people evaluating and
using your work can handle it. Python is fairly mainstream and free enough
that it can foot your bill. But it has various versions and clearly nobody
would advise you to use version 2. Some versions are packaged with many of
the tools you may want to use, such as Anaconda. It depends on your level of
expertise already and how much you want to learn to get this task done. You
make it sound like your kind of work must be done alone, and that can
simplify things but also mean more work for you.

-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Monday, March 13, 2023 2:10 PM
To: python-list@python.org
Subject: Re: Can you process seismographic signals in Python or should I
switch to Matlab ?

On 3/13/2023 11:54 AM, Rich Shepard wrote:> On Mon, 13 Mar 2023, Thomas 
Passin wrote:
 >
 >> No doubt, depending on the data formats used. But it's still going
 >> to be a big task.
 >
 > Thomas,
 >
 > True, but once you have a dataframe with all the information about
 > all the earthquakes you can extract data for every analysis you want
 > to do.
This message would better have gone to the list instead of just me.

I'm not saying that Pandas is a bad choice!  I'm saying that getting all
that data into shape so that it can be ingested into a usable dataframe
will be a lot of hard work.

 > If you've not read Wes McKinney's "Python for Data Analysis: Data
 > Wrangling with Pandas, NumPy, and IPython" I encourage you to do so.

I've been interested in that title, but since I don't currently have any
large, complex data wrangling problems I've put it off.




-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread Thomas Passin
On 3/13/2023 11:54 AM, Rich Shepard wrote:> On Mon, 13 Mar 2023, Thomas 
Passin wrote:

>
>> No doubt, depending on the data formats used. But it's still going
>> to be a big task.
>
> Thomas,
>
> True, but once you have a dataframe with all the information about
> all the earthquakes you can extract data for every analysis you want
> to do.
This message would better have gone to the list instead of just me.

I'm not saying that Pandas is a bad choice!  I'm saying that getting all
that data into shape so that it can be ingested into a usable dataframe
will be a lot of hard work.

> If you've not read Wes McKinney's "Python for Data Analysis: Data
> Wrangling with Pandas, NumPy, and IPython" I encourage you to do so.

I've been interested in that title, but since I don't currently have any
large, complex data wrangling problems I've put it off.




--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread Rich Shepard

On Mon, 13 Mar 2023, Thomas Passin wrote:


No doubt, depending on the data formats used. But it's still going to be a
big task.


Thomas,

True, but once you have a dataframe with all the information about all the
earthquakes you can extract data for every analysis you want to do.

If you've not read Wes McKinney's "Python for Data Analysis: Data Wrangling
with Pandas, NumPy, and IPython" I encourage you to do so.

Regards,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread Thomas Passin

On 3/13/2023 11:23 AM, Rich Shepard wrote:

On Mon, 13 Mar 2023, Thomas Passin wrote:

But what I need is analysis of seismograms from 4,000 seismographs 
world wide to detect P-wave energy distribution underground around 
the earthquake to verify EQ Domino Effect



In that case, you will have to do a great deal of work to get all that
data into a common usable form, cleaned and errors removed. That will 
be a

lot of effort no matter what language you use. In the Matplotlib lesson
you pointed to, the work was already done, for one one earthquake at one
location.


Wouldn't Pandas help here?


No doubt, depending on the data formats used.  But it's still going to 
be a big task.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread Rich Shepard

On Mon, 13 Mar 2023, Thomas Passin wrote:

But what I need is analysis of seismograms from 4,000 seismographs world 
wide to detect P-wave energy distribution underground around the earthquake 
to verify EQ Domino Effect



In that case, you will have to do a great deal of work to get all that
data into a common usable form, cleaned and errors removed. That will be a
lot of effort no matter what language you use. In the Matplotlib lesson
you pointed to, the work was already done, for one one earthquake at one
location.


Wouldn't Pandas help here?

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread Thomas Passin

On 3/13/2023 12:39 AM, a a wrote:

But what I need is analysis of seismograms from 4,000 seismographs world wide 
to detect P-wave energy distribution underground around the earthquake to 
verify EQ Domino Effect


In that case, you will have to do a great deal of work to get all that 
data into a common usable form, cleaned and errors removed.  That will 
be a lot of effort no matter what language you use.  In the Matplotlib 
lesson you pointed to, the work was already done, for one one earthquake 
at one location.


The reference I gave, 
https://towardsdatascience.com/earthquake-time-series-forecasts-using-a-hybr 


id-clustering-lstm-approach-part-i-eda-6797b22aed8c

actually includes a Python script that does this work for some selected 
ranges of data, so it might be a good starting point.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread Thomas Passin

On 3/13/2023 12:39 AM, a a wrote:

But some unknown reasons Matplotlib and numpy crash my Python 3.8 for Windows , 
32-bit and no support is offered


It is possible, using pip, to downgrade versions (e.g., of Matplotlob 
and numpy) to see if you can find versions that work.  Of course moving 
to 64-bit Python >= 3.10 would be better, but if that were possible I 
imagine you would have done it already.


BTW, it would be useful if you said what operating system you are using 
(I've been assuming Windows).


--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-13 Thread a a
On Sunday, 12 March 2023 at 06:17:54 UTC+1, avi.e...@gmail.com wrote:
> I have used GNU Octave as a sort of replacement for MATLAB as a free 
> resource. I have no idea if it might meet your needs. 
> 
> Although Python is a good environment for many things, if you have no 
> knowledge of it yet, it can take a while to know enough and if you just need 
> it for one project, ...
> -Original Message- 
> From: Python-list  On 
> Behalf Of Thomas Passin 
> Sent: Sunday, March 12, 2023 12:02 AM 
> To: pytho...@python.org 
> Subject: Re: Can you process seismographic signals in Python or should I 
> switch to Matlab ?
> On 3/11/2023 6:54 PM, a a wrote: 
> > My project 
> > 
> https://www.mathworks.com/help/matlab/matlab_prog/loma-prieta-earthquake.htm 
> l 
> 
> If your goal is to step through this Matlab example, then clearly you 
> should use Matlab. If you do not have access to Matlab or cannot afford 
> it, then you would have to use something else, and Python would be a 
> prime candidate. However, each of the techniques and graphs in the 
> lesson have been pre-packaged for you in the Matlab case but not with 
> Python (many other case studies on various topics that use Python Python 
> can be found, though). 
> 
> Everything in the Matlab analysis can be done with Python and associated 
> libraries. You would have to learn various processing and graphing 
> techniques. You would also have to get the data from somewhere. It's 
> prepackaged for this analysis and you would have to figure out where to 
> get it. There is at least one Python package that can read and convert 
> Matlab files - I do not remember its name, though. 
> 
> A more important question is whether doing the Matlab example prepares 
> you to do any other analyses on your own. To shed some light on this, 
> here is a post on some rather more advanced analysis using data on the 
> same earthquake, done with Python tools - 
> 
> https://towardsdatascience.com/earthquake-time-series-forecasts-using-a-hybr 
> id-clustering-lstm-approach-part-i-eda-6797b22aed8c
> -- 
> https://mail.python.org/mailman/listinfo/python-list
Thank you my dear friends for your kind opinions.

Matlab is pro, commercial, paid and demo is available for tests only.
So it's hard to dicuss projects, apps in Matlab if cannot be verified by peers.

What is hot today is the following 3D plot animation in Matplotlib

https://twitter.com/gmrpetricca/status/1633477532526817281

But some unknown reasons Matplotlib and numpy crash my Python 3.8 for Windows , 
32-bit and no support is offered

Ok, I can read 100 research papers daily, preview hundreds pages of text from 
search engines.

But what I need is analysis of seismograms from 4,000 seismographs world wide 
to detect P-wave energy distribution underground around the earthquake to 
verify EQ Domino Effect

As you can see below, the Matlab project named in my first submission turned 
into Python project
and EQ energy envelope makes sense.

But I would prefer to join 100+ man project in seismology since it may take me 
months to download
seismograms, process seismograms, preview, select features and build EQ energy 
envelope 3D plots for earthquakes in Turkey alone.

To develop another theory, to get data, process data and get results for 
analysis to verify EQ energy envelope Domino Effect


I am afraid there are no team research projects in seismology.
What is published and discussed is one-man project.



PICOSS: Python Interface for the Classification of
Seismic Signals
A. Buenoa, L. Zuccarellob,c, A. D ́ıaz-Morenod, J. Woolamd, M. Titosb, L.
Garc ́ıaa, I.  ́Alvareza, J. Prudenciob, S. De Angelisd
aDepartment of Signal Theory, Telematic and Communications, University of 
Granada,
Spain.
bDepartment of Theoretical Physics and Cosmos, University of Granada, Spain.
cIstituto Nazionale di Geofisica e Vulcanologia, Sezione di Pisa, Italy
dDepartment of Earth, Ocean and Ecological Sciences, University of Liverpool, UK

https://core.ac.uk/download/pdf/334413225.pdf


seismic-signal 

https://github.com/topics/seismic-signal

STA-LTA Algorithm and Seismometer Trajectory visualization in 3D

Tonumoy /
STA-LTA-Algorithm-and-Seismometer-Trajectory-visualization-in-3D 


https://github.com/Tonumoy/STA-LTA-Algorithm-and-Seismometer-Trajectory-visualization-in-3D


PICOSS

A Python Interface for the Classification of Seismic Signals.

PICOSS is a Python GUI designed as a modular data-curator platform for 
volcano-seismic data analysis. Detection, segmentation and classification. With 
exportability and standardization at its core, users can select automatic or 
manual workflows to annotate seismic data from the suite of included tools.

Originally, PICOSS was designed for the purposes of seismicity research as a 
collaboration between University of Granada (UGR) and Univer

RE: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-11 Thread avi.e.gross
I have used GNU Octave as a sort of replacement for MATLAB as a free
resource. I have no idea if it might meet your needs. 

Although Python is a good environment for many things, if you have no
knowledge of it yet, it can take a while to know enough and if you just need
it for one project, ...

-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Sunday, March 12, 2023 12:02 AM
To: python-list@python.org
Subject: Re: Can you process seismographic signals in Python or should I
switch to Matlab ?

On 3/11/2023 6:54 PM, a a wrote:
> My project
>
https://www.mathworks.com/help/matlab/matlab_prog/loma-prieta-earthquake.htm
l

If your goal is to step through this Matlab example, then clearly you 
should use Matlab. If you do not have access to Matlab or cannot afford 
it, then you would have to use something else, and Python would be a 
prime candidate.  However, each of the techniques and graphs in the 
lesson have been pre-packaged for you in the Matlab case but not with 
Python (many other case studies on various topics that use Python Python 
can be found, though).

Everything in the Matlab analysis can be done with Python and associated 
libraries.  You would have to learn various processing and graphing 
techniques.  You would also have to get the data from somewhere.  It's 
prepackaged for this analysis and you would have to figure out where to 
get it.  There is at least one Python package that can read and convert 
Matlab files - I do not remember its name, though.

A more important question is whether doing the Matlab example prepares 
you to do any other analyses on your own. To shed some light on this, 
here is a post on some rather more advanced analysis using data on the 
same earthquake, done with Python tools -

https://towardsdatascience.com/earthquake-time-series-forecasts-using-a-hybr
id-clustering-lstm-approach-part-i-eda-6797b22aed8c



-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-11 Thread Thomas Passin

On 3/11/2023 6:54 PM, a a wrote:

My project
https://www.mathworks.com/help/matlab/matlab_prog/loma-prieta-earthquake.html


If your goal is to step through this Matlab example, then clearly you 
should use Matlab. If you do not have access to Matlab or cannot afford 
it, then you would have to use something else, and Python would be a 
prime candidate.  However, each of the techniques and graphs in the 
lesson have been pre-packaged for you in the Matlab case but not with 
Python (many other case studies on various topics that use Python Python 
can be found, though).


Everything in the Matlab analysis can be done with Python and associated 
libraries.  You would have to learn various processing and graphing 
techniques.  You would also have to get the data from somewhere.  It's 
prepackaged for this analysis and you would have to figure out where to 
get it.  There is at least one Python package that can read and convert 
Matlab files - I do not remember its name, though.


A more important question is whether doing the Matlab example prepares 
you to do any other analyses on your own. To shed some light on this, 
here is a post on some rather more advanced analysis using data on the 
same earthquake, done with Python tools -


https://towardsdatascience.com/earthquake-time-series-forecasts-using-a-hybrid-clustering-lstm-approach-part-i-eda-6797b22aed8c



--
https://mail.python.org/mailman/listinfo/python-list


RE: Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-11 Thread avi.e.gross
A a,

Consider asking a more specific question. Many things can be done in many
different programming languages.

Are you asking if there are helpers you can use such as modules that
implement parts of the algorithms you need? Are you asking about speed or
efficiency?

Have you considered how few people here are likely to know much about a
specialized field and perhaps a search using a search engine might get you
something like this:

https://www.google.com/search?q=python+process+seimographic+signals&oq=pytho
n+process+seimographic+signals&aqs=chrome..69i57j0i546l5.16718j0j7&sourceid=
chrome&ie=UTF-8

For example:

https://www.geophysik.uni-muenchen.de/~megies/www_obsrise/

You can of course search for say signal processing or whatever makes sense
to you.

My answer, if not clear, is that your question may not be primarily about
Python and about finding whatever environment gives you both access to
software that helps you as well as a language that lets you wrap lots of it
together, make reports and so on. Python is likely a decent choice but
perhaps others are better for your own situation, such as having others
nearby you can learn from.

Good luck.

-Original Message-
From: Python-list  On
Behalf Of a a
Sent: Saturday, March 11, 2023 6:54 PM
To: python-list@python.org
Subject: Can you process seismographic signals in Python or should I switch
to Matlab ?

My project
https://www.mathworks.com/help/matlab/matlab_prog/loma-prieta-earthquake.htm
l
-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Can you process seismographic signals in Python or should I switch to Matlab ?

2023-03-11 Thread a a
My project
https://www.mathworks.com/help/matlab/matlab_prog/loma-prieta-earthquake.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: INSTRUCTOR SOLUTIONS MANUAL Linear Systems And Signals 2nd ED by B P Lathi

2017-10-02 Thread Steve D'Aprano
On Tue, 3 Oct 2017 12:54 pm, mosama221...@gmail.com wrote:

> i need instructor of second edition of linear system and signals by lathi

Don't reply to spammers and don't reply to them. They are the scum of the earth.

They are literally criminals, they use computer viruses and malware to hijack
people's computers to send their spam, and you want to trust them and buy from
them?


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: INSTRUCTOR SOLUTIONS MANUAL Linear Systems And Signals 2nd ED by B P Lathi

2017-10-02 Thread mosama221122
i need instructor of second edition of linear system and signals by lathi
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread Steve D'Aprano
On Sun, 6 Aug 2017 03:18 am, Michael Torrie wrote:

> Forgive Steven for his off-topic reply. I assume he's trying to goad you
> into having a more specific subject line.  He knows darn well what PyQt,
> even if he has no experience with it.

Pardon me, I said:

"I don't know what Qt signals are."

I know what Qt is. I don't know what Qt signals are, just as I said.

Well I do now, thanks to Veek answering his own question with a good explanation
of Qt slots.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread Michael Torrie
On 08/05/2017 08:28 AM, veek wrote:
> 

At a certain point beyond the general stuff, questions about PyQt might
be better suited to the PyQt mailing list, hosted by the company that
maintains PyQt:

https://www.riverbankcomputing.com/mailman/listinfo/pyqt


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread Michael Torrie
On 08/05/2017 12:19 PM, Marko Rauhamaa wrote:
> I would express it as just saying that the Qt developers appropriated
> the word "signal" for what is simply a callback.

I'd say a slot is a callback.  A signal is the designation of something
that will trigger callbacks.

> Years back I took a brief loook at Qt. I had heard that one of their
> great selling points was that they did C++. At the time, C++ was my
> bread and butter, and I had been baffled at how bad C++ was at
> expressing such a basic thing as callbacks.
> 
> Turns out Qt didn't do callbacks using C++. Instead they specified a
> sort of macro language to express callbacks and offered what was known
> as a "metacompiler" that converted those macros into real C++.

Off-topic, but probably still worth talking about, since the OP does
appear interested in Qt internals and how they relate to Python.

As for Qt not being really C++, that's only partially true these days.
Qt code you write is actual C++, directly compile-able with any
standards-compliant C++ compiler. moc, the metacompiler you're referring
to, generates some helper code that is required to tie the Qt objects
together.  And you can argue this is only necessary because of
deficiencies in C++ (at least pre-STL days).  But this is no different
or burdensome than requiring a step to compile an XML ui file to code
like many/most UI toolkits do.

The biggest problem with moc in my mind is that it hides the fact that
signal emission is done by name in the Qt engine, using string lookups
and comparisons. In your code they look like actual identifiers but moc
generates string equivalents in the meta class code. This can lead to
really weird bugs.  It's been a long time since I ran into this problem
so I can't remember the specifics. I'm not sure if this problem would
manifest itself in Python code, but I suspect it might.

> It was a big disappointment both with respect to C++ and Qt.
> 
> Now, the Standard Template Library offered elaborate macros (aka functor
> templates) that allowed you to express callbacks with zero, one or two
> arguments (in a cumbersome way). Boost, a famous C++ class library,
> added functor support to three, four, five, six, seven, eight, nine,
> and--hear this!--TEN arguments.

Yeah Qt has never used templates because they didn't exist when Qt was
first started. Now I think you could use templates to do a lot of what
moc does, and indeed Gtkmm uses templates to make a very nice, very
native C++ binding for GTK+.  I have had to, on occasion, make my own
templates for gtkmm when the number of parameters I needed to bind was
different than the prefab templates provided.  Templates can be really
cumbersome.

One area that the template-based GTKmm really shone compared to Qt was
that, in C++ at least, signatures between the signal and slot were
checked at compile time, thanks to templates.  In Qt, they end up being
essentially bare function pointers (might get a runtime error? I can't
remember).

> All this nonsense because it hadn't occurred to Bjarne Stroustrup to
> define so-called method pointers in a sane manner. It was left to
> another Dane, Anders Hejlsberg, to demonstrate how they ought to have
> been defined, namely, as delegates (as in Delphi and C#). Unfortunately,
> it was too late for C++.
> 
> Now, I'm hearing C++ supports proper closures:  http://en.cppreference.com/w/cpp/language/lambda>. I wonder if Qt would
> eventually migrate to them.
> 
> At any rate, Python never had to come up with such tricks for callbacks.
> Python's closure syntax is maybe the most natural there is. Too bad if
> PyQt confuses Python programmers with "signals" and "slots" when they
> are simply methods.

True enough. When you work with PyQt, unfortunately these C++ details do
leak through, which is the biggest weakness of PyQt (and also PySide).
So I guess that's reason enough to be familiar with the warts.

Despite the warts, PyQt is my go-to toolkit for doing the simple GUI
stuff I need, as it is easy to install and run on any platform and looks
great.  I wrote a simple compatibility shim to let me use both PySide
and PyQt4 with the same code.  That way if I need to release code in a
non-GPL way, I can just switch to PySide.

PySide had its own issues because of how the bindings are made. One of
them is that occasionally PySide drops a reference to a Qt C++ object,
which can lead to a segfault.

And I have no idea the state of PySide for Qt5.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread Vincent Vande Vyvre

Le 05/08/17 à 16:28, veek a écrit :

1. What exactly is a signal. In hardware, an interrupt can be viewed as a
signal and the voltage on a pin will suddenly jump to +5V as an indicator
that an interrupt has occurred. With Qt signals - if a widget-c++ code has
to 'signal' an event - what does it do?

As a consequence of not understanding the above..

2. How do you connect a single signal to multiple slots? Do the
slots/methods get called one by one? or are they treated as independent
threads and run on different cores?

You have to connect yours slots each by each.
self.my_button.clicked.connect(self.foo)
self.my_button.clicked.connect(self.baz)
...
Be care you can't know the order of the execution of foo and baz.
Any thread will be created for that, the binding will be executed into 
the main loop of your app.
But, if your signal is emitted from a thread, the slot will be executed 
into the main thread, this is a great advantage, your slot can interact 
safely with the graphics part of your app.


3. pg 130 of Summerfield

class ZeroSpinBox(QObject):
def __init__(self, parent=None):
   super(...blah initialize QObject with parent
   self.connect(self, SIGNAL("valuedChanged(int)"), self.checkzero)

def checkzero(self):
   if self.value() == 0:
  self.emit(SIGNAL("atzero"), self.zeros)

basically when SpinBox gets set to zero we emit 'atzero' and return a zeros
counter.

What i don't get is the valueChanged(int) bit.. he clearly defines an (int)
being passed to checkzero so shouldn't the definition reflect the same?
Mistake?
This is the old signal-slot methods, I encourage you to use the new (new 
but not recent) method

Like this:
from QtCore import pyqtSignal

class ZeroSpinBox(QObject):
   atZero = pyqtSignal(int)
   def __init__(self, parent=None):
  super(...blah initialize QObject with parent
  self.valuedChanged.connect(self.checkzero)

   def checkzero(self, value):
  if not value:
 # maybe increment self.zeros ?
 self.atzero.emit(self.zeros)


A. additionally I did not understand short circuit signals where you can
drop the (type1, type2) in the signature and just do
SIGNAL("atzero")

Is this doable ONLY in emit() or also in connect()??

I don't know, never used this construction of code.



4. pg 131 'any data can be passed as arguments to the emit method and they
can be passed as Python objects'

self.emit(SIGNAL("atzero"), 10, 20, 30) or
self.emit(SIGNAL("atzero"), [10, 20, 30])
does he mean i can pass a SINGLE OBJECT of any python type or does he mean
multiple independent containers?
(assuming the definition matches)

When you define your signal you can use any Python type
sig = pyqtSignal(int, float, str, str, ...)


5. He says 'a signal with one argument is a Qt signal or a non-short-circuit
Python signal'

So if I have a Qt widget in C++ and it emits a valueChanged(int) signal..
okay he's going to have to convert our asm/x86 int to python-integer and
then call the python-method that was mapped to 'valueChanged' with the
python-integer argument OR the signal is being generated from Python code
itself AND WILL be converted to C++ datatype - huh why??

The wrapper use simply the CPython "PyLong_AsLong" or "PyUnicode_FromString"
or "Py_BuildValue" or other and you get always a Python object.


I'm guessing there's some dispatch code that maintains a mapping table?? SO
why can't it differentiate between inhouse python widget and Qt-c++ widget??


6. "If we use the SIGNAL() function with a signalSignature (a possibly empty
parenthesized list of comma-separated PyQt types)..."??

how can it be an empty () list..?? If there's a list it's no longer empty..

7. What exactly is a Python signal vs a Qt signal originating from a C++-
asm-widget?? PyQt is a wrapper around C++Qt so.. where are the python
widgets??

8.
class TaxRate(QObject):
   def __init__(self):
 super(TaxRate, self).__init__()
 self.__rate = 17.5

   def rate(self):
 return self.__rate

   def setRate(self, rate):
 if rate != self.__rate:
self.__rate = rate
self.emit(SIGNAL("rateChanged"), self.__rate)

def rateChanged(value):
print "TaxRate changed to %.2f%%" % value

vat = TaxRate()
vat.connect(vat, SIGNAL("rateChanged"), rateChanged)
vat.setRate(17.5) # No change will occur (new rate is the same)
vat.setRate(8.5) # A change will occur (new rate is different)

Isn't this a mistake? self.connect( should be:
vat.connect(vat, SIGNAL("rateChanged"), rate)


Again, use the new syntaxe (new but not recent) it's more clear.

Vincent
--
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread Marko Rauhamaa
Michael Torrie :

> Basically a signal emission is a call to the main loop that indicates
> that an event has occurred, and then the main loop sees if there are
> any registered callbacks that want to be notified of this event, and
> if so it calls them, letting them execute. This is how event-driven
> programming works. The concept of signals and slots is very similar to
> explicit registering of callbacks in function. It differs only in
> form.

I would express it as just saying that the Qt developers appropriated
the word "signal" for what is simply a callback.

Years back I took a brief loook at Qt. I had heard that one of their
great selling points was that they did C++. At the time, C++ was my
bread and butter, and I had been baffled at how bad C++ was at
expressing such a basic thing as callbacks.

Turns out Qt didn't do callbacks using C++. Instead they specified a
sort of macro language to express callbacks and offered what was known
as a "metacompiler" that converted those macros into real C++.

It was a big disappointment both with respect to C++ and Qt.

Now, the Standard Template Library offered elaborate macros (aka functor
templates) that allowed you to express callbacks with zero, one or two
arguments (in a cumbersome way). Boost, a famous C++ class library,
added functor support to three, four, five, six, seven, eight, nine,
and--hear this!--TEN arguments.

All this nonsense because it hadn't occurred to Bjarne Stroustrup to
define so-called method pointers in a sane manner. It was left to
another Dane, Anders Hejlsberg, to demonstrate how they ought to have
been defined, namely, as delegates (as in Delphi and C#). Unfortunately,
it was too late for C++.

Now, I'm hearing C++ supports proper closures: http://en.cppreference.com/w/cpp/language/lambda>. I wonder if Qt would
eventually migrate to them.

At any rate, Python never had to come up with such tricks for callbacks.
Python's closure syntax is maybe the most natural there is. Too bad if
PyQt confuses Python programmers with "signals" and "slots" when they
are simply methods.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread Michael Torrie
Forgive Steven for his off-topic reply. I assume he's trying to goad you
into having a more specific subject line.  He knows darn well what PyQt,
even if he has no experience with it.

And of course, as always you will want to post a complete, working
example that we can see and comment on, rather than extracts of the
code.  It's much harder to comment on that.

On 08/05/2017 08:28 AM, veek wrote:
> 1. What exactly is a signal. In hardware, an interrupt can be viewed as a 
> signal and the voltage on a pin will suddenly jump to +5V as an indicator 
> that an interrupt has occurred. With Qt signals - if a widget-c++ code has 
> to 'signal' an event - what does it do?

Basically a signal emission is a call to the main loop that indicates
that an event has occurred, and then the main loop sees if there are any
registered callbacks that want to be notified of this event, and if so
it calls them, letting them execute. This is how event-driven
programming works.  The concept of signals and slots is very similar to
explicit registering of callbacks in function. It differs only in form.

So it sounds from your post that the book you are following is older and
uses some of the older forms for signals and slots in PyQt.  In recent
years, PyQt has made some things nicer, make making signals just be
members of the class that you can access through python as if they were
a member of the instance.  so my code in response to your questions will
reflect this newer style. I recommend you look at the various online
tutorials for PyQt (I still am using PyQt4, but PyQt5 will be nearly the
same).

> As a consequence of not understanding the above..
> 
> 2. How do you connect a single signal to multiple slots? Do the 
> slots/methods get called one by one? or are they treated as independent 
> threads and run on different cores?

You simply have more than one connect() call.  for example:

button1.clicked.connect(callback1)
button1.clicked.connect(callback2)

Both callbacks will run when button1 emits its "clicked" signal.

Then the callbacks are executed in some kind of order when the signal is
emitted, one at a time.  GUIs are typically single-threaded.  That's why
it's important to not have long-running code in a callback.  If you do
need to do something in a call back that takes a while, you could spawn
a thread and turn the work over to a thread, and then return control of
the GUI thread back to the main loop.

> 
> 3. pg 130 of Summerfield
> 
> class ZeroSpinBox(QObject):
   
I'm guessing that should be QSpinBox, not QObject, as this class is just
adding behavior to the spinbox.  If the book really has it as QObject, I
would suspect it is a mistake.  But without seeing the entire example
program, I cannot say.

>def __init__(self, parent=None):
>   super(...blah initialize QObject with parent
>   self.connect(self, SIGNAL("valuedChanged(int)"), self.checkzero)
> 
>def checkzero(self):
>   if self.value() == 0:
>  self.emit(SIGNAL("atzero"), self.zeros)
> 
> basically when SpinBox gets set to zero we emit 'atzero' and return a zeros 
> counter.
> 
> What i don't get is the valueChanged(int) bit.. he clearly defines an (int) 
> being passed to checkzero so shouldn't the definition reflect the same? 
> Mistake?

Normally it should match the signature, yes.  Whether this is a mistake,
I don't know.  I believe PyQt could be ignoring the parameters the slot
callback doesn't have defined. And since he's calling self.value() to
read the actual value, he doesn't really need the int parameter, though
if it were me I'd use the parameter and not call self.value() at all.

> A. additionally I did not understand short circuit signals where you can
> drop the (type1, type2) in the signature and just do
> SIGNAL("atzero")
> 
> Is this doable ONLY in emit() or also in connect()??

As far as I know, only in the emit().  I'm not familiar with this "short
circuit" thing.  In fact I've never heard of it and have done a few
things in PyQt.

For defining signals, PyQt has defined a new method for creating signals
that's much cleaner than using the SIGNAL() call:

class ZeroSpinBox(QSpinbox):
atzero = PyQt4.pyqtSignal() #could list arguments here if desired
someother = PyQt4.pyqtSignal('int','bool')

...

def checkzero(self, value):
if value == 0:
self.atzero.emit()

Note that parameters to pyqtSignal can be either Python types that PyQt
can marshall (int, float,str, any QObject-derived class etc), or C++
types as a name in a string.

> 4. pg 131 'any data can be passed as arguments to the emit method and they 
> can be passed as Python objects'
> 
> self.emit(SIGNAL("atze

Re: Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread veek
Steve D'Aprano wrote:

> On Sun, 6 Aug 2017 12:28 am, veek wrote:
> 
>> 1. What exactly is a signal. In hardware, an interrupt can be viewed as a
>> signal and the voltage on a pin will suddenly jump to +5V as an indicator
>> that an interrupt has occurred. With Qt signals - if a widget-c++ code
>> has to 'signal' an event - what does it do?
> 
> I don't know what Qt signals are.
> 
> Unix signals are an interrupt mechanism used by Unix and Linux operating
> systems. Windows may support them as well. The "kill" system command sends
> signals to a specific running process, which will then jump to a specific
> piece of code. The command is called "kill" because the main use for this
> is to terminate processes.
> 
> Python supports these signals:
> 
> https://docs.python.org/3/library/signal.html
> 
> https://pymotw.com/3/signal/index.html
> 
> 
>  
>> As a consequence of not understanding the above..
>> 
>> 2. How do you connect a single signal to multiple slots? Do the
>> slots/methods get called one by one? or are they treated as independent
>> threads and run on different cores?
> 
> What are slots?
> 
> 
>> 3. pg 130 of Summerfield
> 
> What is Summerfield?
> 
> 
> 

The book I'm reading is: Mark Summerfield - Rapid GUI Programming with 
Python and Qt.

PyQt is a wrapper around the C++/Qt library and they have a Signal and Slot 
mechanism for doing GUI/event-driven work - Qt doesn't have it.

Basically if you have a widget like QSpinBox it'll be rendered/drawn using a 
C++ Qt library (which is fast). 

Anyway, widgets support 'events' like mouse-over  and click and they are 
constantly generating events which are mostly ignored by the PyQt library 
and discarded. However if you decide you want to handle an event then you 
use PyQt's signal/slot mechanism: slot's a method and signal looks to be 
basically a string.

Eg:

class Form(QWidget):

  def __init__(self, parent=None):
 super(Form, self).__init__(parent) #init QWidget with parent is set
 combo = QComboBox()
 self.connect(combo, SIGNAL("some_event(int)"),self.combo_event_handler)

  def combo_event_handler(self, i):
 pass

combo_event_handler's the slot.. it's just a python OR Qt method.
QComboBox() will result in a combo box being drawn when the app is started 
via 
app = QApplication()
app.exec_()

then if I mouse over the widget it'll generate an 'event'/'signal'
and call the handler to process - event driven programming

"some_event()" is a string being passed to connect() and that's a function 
signature that tells connect what types the handler expects. 
combo_event_handler can be a Qt method in which case conversion occurs to 
C++ data types but it can also be a python method and if you short ckt then 
no conversion to C++ types occurs.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread Steve D'Aprano
On Sun, 6 Aug 2017 12:28 am, veek wrote:

> 1. What exactly is a signal. In hardware, an interrupt can be viewed as a
> signal and the voltage on a pin will suddenly jump to +5V as an indicator
> that an interrupt has occurred. With Qt signals - if a widget-c++ code has
> to 'signal' an event - what does it do?

I don't know what Qt signals are.

Unix signals are an interrupt mechanism used by Unix and Linux operating
systems. Windows may support them as well. The "kill" system command sends
signals to a specific running process, which will then jump to a specific piece
of code. The command is called "kill" because the main use for this is to
terminate processes.

Python supports these signals:

https://docs.python.org/3/library/signal.html

https://pymotw.com/3/signal/index.html


 
> As a consequence of not understanding the above..
> 
> 2. How do you connect a single signal to multiple slots? Do the
> slots/methods get called one by one? or are they treated as independent
> threads and run on different cores?

What are slots?


> 3. pg 130 of Summerfield

What is Summerfield?





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Signals and Slots - Summerfield - what exactly is a signal?

2017-08-05 Thread veek
1. What exactly is a signal. In hardware, an interrupt can be viewed as a 
signal and the voltage on a pin will suddenly jump to +5V as an indicator 
that an interrupt has occurred. With Qt signals - if a widget-c++ code has 
to 'signal' an event - what does it do?

As a consequence of not understanding the above..

2. How do you connect a single signal to multiple slots? Do the 
slots/methods get called one by one? or are they treated as independent 
threads and run on different cores?

3. pg 130 of Summerfield

class ZeroSpinBox(QObject):
   def __init__(self, parent=None):
  super(...blah initialize QObject with parent
  self.connect(self, SIGNAL("valuedChanged(int)"), self.checkzero)

   def checkzero(self):
  if self.value() == 0:
 self.emit(SIGNAL("atzero"), self.zeros)

basically when SpinBox gets set to zero we emit 'atzero' and return a zeros 
counter.

What i don't get is the valueChanged(int) bit.. he clearly defines an (int) 
being passed to checkzero so shouldn't the definition reflect the same? 
Mistake?

A. additionally I did not understand short circuit signals where you can
drop the (type1, type2) in the signature and just do
SIGNAL("atzero")

Is this doable ONLY in emit() or also in connect()??


4. pg 131 'any data can be passed as arguments to the emit method and they 
can be passed as Python objects'

self.emit(SIGNAL("atzero"), 10, 20, 30) or 
self.emit(SIGNAL("atzero"), [10, 20, 30])
does he mean i can pass a SINGLE OBJECT of any python type or does he mean 
multiple independent containers?
(assuming the definition matches)

5. He says 'a signal with one argument is a Qt signal or a non-short-circuit 
Python signal' 

So if I have a Qt widget in C++ and it emits a valueChanged(int) signal.. 
okay he's going to have to convert our asm/x86 int to python-integer and 
then call the python-method that was mapped to 'valueChanged' with the 
python-integer argument OR the signal is being generated from Python code 
itself AND WILL be converted to C++ datatype - huh why??

I'm guessing there's some dispatch code that maintains a mapping table?? SO 
why can't it differentiate between inhouse python widget and Qt-c++ widget??


6. "If we use the SIGNAL() function with a signalSignature (a possibly empty 
parenthesized list of comma-separated PyQt types)..."??

how can it be an empty () list..?? If there's a list it's no longer empty..

7. What exactly is a Python signal vs a Qt signal originating from a C++-
asm-widget?? PyQt is a wrapper around C++Qt so.. where are the python 
widgets??

8. 
class TaxRate(QObject):
  def __init__(self):
super(TaxRate, self).__init__()
self.__rate = 17.5

  def rate(self):
return self.__rate

  def setRate(self, rate):
if rate != self.__rate:
   self.__rate = rate
   self.emit(SIGNAL("rateChanged"), self.__rate)

def rateChanged(value):
print "TaxRate changed to %.2f%%" % value

vat = TaxRate()
vat.connect(vat, SIGNAL("rateChanged"), rateChanged)
vat.setRate(17.5) # No change will occur (new rate is the same)
vat.setRate(8.5) # A change will occur (new rate is different)

Isn't this a mistake? self.connect( should be:
vat.connect(vat, SIGNAL("rateChanged"), rate)




-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Alternative to signals in threads

2017-03-08 Thread woooee
Use multiprocessing since you want to do multiple things at once 
https://pymotw.com/2/multiprocessing/basics.html  If I understand you 
correctly, once the string is found you would terminate the process, so you 
would have to signal the calling portion of the code using a Manager dictionary 
or list..  I am not that knowledgeable about multiprocessing, so this is 
probably the long way around the barn.
import time
from multiprocessing import Process, Manager


def test_f(test_d):
   ctr=0
   while True:
  ctr += 1
  print "test_f", test_d["QUIT"], ctr
  time.sleep(1.0)
  if ctr > 5:
 test_d["QUIT"]=True
  
if __name__ == '__main__':
   ## define the dictionary to be used to communicate
   manager = Manager()
   test_d = manager.dict()
   test_d["QUIT"] = False

   ## start the process
   p = Process(target=test_f, args=(test_d,))
   p.start()
   
   ## check the dictionary every half-second
   while not test_d["QUIT"]:
  time.sleep(0.5)
   p.terminate()
-- 
https://mail.python.org/mailman/listinfo/python-list


Alternative to signals in threads

2017-03-08 Thread saatomic
I've been unsuccessfully looking for an alternative for signals, that works in 
threads.

After updating a script of mine from being single-threaded to being 
multi-threaded, I realised that signals do not work in threads.

I've used signals to handle blocking operations that possibly take forever like:


signal.signal(signal.SIGALRM, wait_timeout)
# wait_timeout simply does: raise Exception("timeout")
signal.setitimer(signal.ITIMER_REAL,5)
# So a timer of 5 seconds start and I run my operation
try:
       p = Popen(["tool", "--param"], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
       for line in p.stdout:
           if "STRING" in str(line):
                     signal.setitimer(signal.ITIMER_REAL,0)
                     p.terminate()
                     print("Success")
except:
       p.terminate()
       print("Timeout")


Now this works great with a single thread, but doesn't work at all with 
multiple threads.
A more throughout example can be found here: 
https://gist.github.com/saatomic/841ddf9c5142a7c75b03daececa8eb17 

What can I use instead of signals in this case?

Thanks and kind regards,
SaAtomic
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Threads in Python 3.5 or so

2016-10-24 Thread Dan Stromberg
On Mon, Oct 10, 2016 at 12:05 AM, dieter  wrote:
> Dan Stromberg  writes:
>> I have a program http://stromberg.dnsalias.org/~dstromberg/looper/
>> that I use and maintain.
>>
>> It's like GNU parallel or similar - yet another "run n processes, m at
>> a time" implementation.  Interestingly, I've only used/tested it on
>> Linux, but it's under a Microsoft copyright because Microsoft acquired
>> a Linux company I was working for.
>>
>> Anyway, it seems to work well, except one annoying bug.
>>
>> That bug is: if you control-C the top-level process, all the
>> subprocesses are left running.
>>
>> I've been thinking about making it catch SIGINT, SIGTERM and SIGHUP,
>> and having it SIGKILL its active subprocesses upon receiving one of
>> these signals.
>>
>> However, it's multithreaded, and I've heard that in CPython, threads
>> and signals don't mix well.
>
> I would not state it this way.
>
> Signals are delivered to processes (not process threads).
> That leads to the question which thread (in a multi thread application)
> will handle a signal when it arrives.
> In Python, the design decision has been not to use the currently
> running thread (which may not be a Python thread at all or
> may have executed Python code but at the moment runs C code outside
> of Python) but let the signal be handled deterministically by
> the main thread (once it starts again to execute Python code).
> This looks like a sane decision to me.

Thank you for the clear explanation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyQT - Signals and Slots?

2016-10-10 Thread Michael Torrie
On 10/10/2016 07:32 AM, Veek M wrote:
> Whaaa...t?? Could someone explain what exactly is his grand design 
> besides being awfully circuitous? So he has some other Form thingy.. and 
> in that he sets up another mapping from ZeroSpinBox.atzero --> 
> ZeroSpinBox.announce  where's announce and atzero defined?

In your example code, "atzero" is implicitly defined as a signal in the
connect() call.  Under the hood in Qt, signals are all dispatched by
strings when you emit() the signal.  PyQt does allow you to define
signals in a more pythonic way using class variables:

class Foo(QWidget):
atzero = SIGNAL( signature )

The signature can be a list of python types, or strings describing the
C++ types.  This is where the C++ nature of Qt leaks into PyQt.  In C++
since the moc compiler takes C++ code and C++ type names and generates a
meta-class that defines signals in terms of strings (moc does basic
compile-time type checking), in Python we also have to provide
signatures in strings also if we need something more than core python
types (int, bool, etc).  This signature helps PyQt (well Qt really)
marshal the types properly when the signal's callback is called.

But yes the example is convoluted and circuitous.  I think it's just to
demonstrate how signals and slots work, though.  That's what the
comments make clear.  This isn't how you'd implement a real widget with
customized behavior.

In general I don't think widgets normally want to catch their own
signals.  There are other mechanisms for that.  Usually you subclass the
widget and then override the appropriate *Event() method. For example,
to do something special on value changes I believe you'd subclass
QSpinBox and override the changeEvent() method. Inside that you would
get your value, do your logic, and potentially emit a custom signal. And
of course calling the parent changeEvent() to propagate the event
through to the parent class.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyQT - Signals and Slots?

2016-10-10 Thread Veek M
Mark Summerfield wrote:

> 
> The ZeroSpinBox is a tiny example designed to show how the signal/slot
> mechanism works. It is just a QSpinBox with the addition of
> remembering how many times (all the) ZeroSpinBox(es) have had a 0
> value.
> 
> Nowadays the connections would be made with a new improved syntax:
> 
> self.connect(self, SIGNAL("valueChanged(int)"), self.checkzero) # OLD
> self.valueChanged.connect(self.checkzero) # NEW
> # or
> self.valueChanged[int].connect(self.checkzero) # NEW
> 
> Similarly the emit:
> self.emit(SIGNAL("atzero"), self.zeros) # OLD
> self.atzero.emit(self.zeros) # NEW
> 
> What's happening inside ZeroSpinBox? Whenever its value is set to 0 it
> calls its own checkzero() method, and this in turn emits an atzero
> signal with the number of zeros so far. Why does it do this? Just to
> show the mechanism. It doesn't matter whether you connect a widget to
> itself (unusual but done here), or to another widget (the norm).
> 
> See the book's website https://www.qtrac.eu/pyqtbook.html
> for all the source code including some updated with the new syntax.
> (But the book is old, so even the Python 3.1 examples aren't as
> Pythonic as they would be written in Python 3.4+.)

ah - okay, so i was on the right track - thanks :) cool that you hang 
out here :) 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyQT - Signals and Slots?

2016-10-10 Thread Mark Summerfield

The ZeroSpinBox is a tiny example designed to show how the signal/slot
mechanism works. It is just a QSpinBox with the addition of remembering
how many times (all the) ZeroSpinBox(es) have had a 0 value.

Nowadays the connections would be made with a new improved syntax:

self.connect(self, SIGNAL("valueChanged(int)"), self.checkzero) # OLD
self.valueChanged.connect(self.checkzero) # NEW
# or
self.valueChanged[int].connect(self.checkzero) # NEW

Similarly the emit:
self.emit(SIGNAL("atzero"), self.zeros) # OLD
self.atzero.emit(self.zeros) # NEW

What's happening inside ZeroSpinBox? Whenever its value is set to 0 it
calls its own checkzero() method, and this in turn emits an atzero signal
with the number of zeros so far. Why does it do this? Just to show the
mechanism. It doesn't matter whether you connect a widget to itself
(unusual but done here), or to another widget (the norm).

See the book's website https://www.qtrac.eu/pyqtbook.html
for all the source code including some updated with the new syntax.
(But the book is old, so even the Python 3.1 examples aren't as Pythonic as 
they would be written in Python 3.4+.)
-- 
https://mail.python.org/mailman/listinfo/python-list


PyQT - Signals and Slots?

2016-10-10 Thread Veek M
I'm reading Rapid GUI Programming - Mark Summerfield with Python and QT 
pg 131. Basically the mechanism is an event table which maps a 'signal' 
to a 'function/slot' -correct?

  self.connect(dial, SIGNAL("valueChanged(int)"), spinbox.setValue)

Here, dial.valueChanged -> spinbox.setValue

 s.connect(w, SIGNAL("signalSignature"), functionName)
 s.connect(w, SIGNAL("signalSignature"), instance.methodName)
 s.connect(w, SIGNAL("signalSignature"), instance, 
SLOT("slotSignature"))

Here, w.signalSignature -> functionName
-> instance.methodName
-> instance.slotSignature

If signalSignature is a C++ implemented thingy then we got to pass type 
info as part of the mapping so "signalSignature(int, float, const char 
*). PyQT signals are any type and any number of args..


If the Slot-function is implemented in C++ it's better to use the SLOT() 
mechanism:
 self.connect(dial, SIGNAL("valueChanged(int)"), spinbox, 
SLOT("setValue(int)"))
Here, we are mapping dial.valueChanged(int) --> spinbox.setValue(int)


The part i found tricky was this:

class ZeroSpinBox(QSpinBox):
zeros = 0
def __init__(self, parent=None):
super(ZeroSpinBox, self).__init__(parent)
self.connect(self, SIGNAL("valueChanged(int)"), self.checkzero)

def checkzero(self):
if self.value() == 0:
self.zeros += 1
self.emit(SIGNAL("atzero"), self.zeros)

ZeroSpinBox.valueChanged -> ZeroSpinBox.checkzero? Why is he mapping 
back to himself? Shouldn't it be widget-to-widget?

Then he raises a signal 'atzero' with one arg - the lack of a atzero() 
implies it's a 'short-circuit' signal so self.zeroes is a python data 
type. And in the book he says:

###
Here is how we connect to the signal in the form’s __init__() method:
zerospinbox = ZeroSpinBox()
...
self.connect(zerospinbox, SIGNAL("atzero"), self.announce)
Again, we must not use parentheses because it is a short-circuit signal. 
And
for completeness, here is the slot it connects to in the form:
def announce(self, zeros):
print "ZeroSpinBox has been at zero %d times" % zeros
###

Whaaa...t?? Could someone explain what exactly is his grand design 
besides being awfully circuitous? So he has some other Form thingy.. and 
in that he sets up another mapping from ZeroSpinBox.atzero --> 
ZeroSpinBox.announce  where's announce and atzero defined?





-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Threads in Python 3.5 or so

2016-10-10 Thread dieter
Dan Stromberg  writes:
> I have a program http://stromberg.dnsalias.org/~dstromberg/looper/
> that I use and maintain.
>
> It's like GNU parallel or similar - yet another "run n processes, m at
> a time" implementation.  Interestingly, I've only used/tested it on
> Linux, but it's under a Microsoft copyright because Microsoft acquired
> a Linux company I was working for.
>
> Anyway, it seems to work well, except one annoying bug.
>
> That bug is: if you control-C the top-level process, all the
> subprocesses are left running.
>
> I've been thinking about making it catch SIGINT, SIGTERM and SIGHUP,
> and having it SIGKILL its active subprocesses upon receiving one of
> these signals.
>
> However, it's multithreaded, and I've heard that in CPython, threads
> and signals don't mix well.

I would not state it this way.

Signals are delivered to processes (not process threads).
That leads to the question which thread (in a multi thread application)
will handle a signal when it arrives.
In Python, the design decision has been not to use the currently
running thread (which may not be a Python thread at all or
may have executed Python code but at the moment runs C code outside
of Python) but let the signal be handled deterministically by
the main thread (once it starts again to execute Python code).
This looks like a sane decision to me.


Your problem description indicates that the problem is not
with signal handling by threads but with signal delivery by
the operating system.

In Linux, SIGINT signals in response to a "CTRL-C" are delivered
to the process group of the "control terminal".
Thus, with appropriate Linux calls, you can control whether or not
such a SIGINT is delivered to a subprocess.

Other operating systems may not provide such a control or it may
need different (OS dependent) calls.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Threads in Python 3.5 or so

2016-10-09 Thread Marko Rauhamaa
Dan Stromberg :
> That bug is: if you control-C the top-level process, all the
> subprocesses are left running.

Sorry, don't have a solution for your particular Python situation.

> I've been thinking about making it catch SIGINT, SIGTERM and SIGHUP,
> and having it SIGKILL its active subprocesses upon receiving one of
> these signals.

SIGKILL is probably a bad idea. It doesn't give the subprocess any
opportunity for a graceful exit. For example, Python's try/finally
blocks will fail to work as advertised. Better use a catchable signal.

> However, it's multithreaded, and I've heard that in CPython, threads
> and signals don't mix well.

Python does confuse matters, but both threads and signals are
problematic entities under Linux. You need to be very well versed in the
semantics of both operating system concepts (man 7 pthreads, man 7
signal).


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Threads in Python 3.5 or so

2016-10-09 Thread Paul Rubin
Dan Stromberg  writes:
> That bug is: if you control-C the top-level process, all the
> subprocesses are left running.

Are you setting the daemon flag?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Signals and Threads in Python 3.5 or so

2016-10-09 Thread Chris Angelico
On Mon, Oct 10, 2016 at 10:52 AM, Dan Stromberg  wrote:
> That bug is: if you control-C the top-level process, all the
> subprocesses are left running.
>
> I've been thinking about making it catch SIGINT, SIGTERM and SIGHUP,
> and having it SIGKILL its active subprocesses upon receiving one of
> these signals.
>
> However, it's multithreaded, and I've heard that in CPython, threads
> and signals don't mix well.

Generally, expect SIGINT  to be handled by the main thread, and code
accordingly. But I've never used the low-level thread and _thread
modules, so I'd be inclined to follow through with the TODO and make
it use threading instead.

This simple example appears to work fine on my system (Debian Stretch,
Linux 4.6, amd64), but I can't make any hard-and-fast guarantees.

import threading
import signal
import random
import time

halt = False

def thread():
global halt
try:
print(threading.current_thread(), "-- start")
for i in range(random.randrange(10, 20)):
time.sleep(1)
if halt: break
print(threading.current_thread(), "--", i)
except KeyboardInterrupt:
print(threading.current_thread(), "-- SIGINT")
halt = True
print(threading.current_thread(), "-- end")

for i in range(5):
threading.Thread(target=thread).start()
thread()


Hit Ctrl-C and all threads will quickly terminate.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Signals and Threads in Python 3.5 or so

2016-10-09 Thread Dan Stromberg
I have a program http://stromberg.dnsalias.org/~dstromberg/looper/
that I use and maintain.

It's like GNU parallel or similar - yet another "run n processes, m at
a time" implementation.  Interestingly, I've only used/tested it on
Linux, but it's under a Microsoft copyright because Microsoft acquired
a Linux company I was working for.

Anyway, it seems to work well, except one annoying bug.

That bug is: if you control-C the top-level process, all the
subprocesses are left running.

I've been thinking about making it catch SIGINT, SIGTERM and SIGHUP,
and having it SIGKILL its active subprocesses upon receiving one of
these signals.

However, it's multithreaded, and I've heard that in CPython, threads
and signals don't mix well.

Is this still an issue in CPython 3.5?  If yes, how can I work around it?

Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: In pyqt, some signals seems not work well

2013-08-04 Thread Jack

On 2013/8/5 2:20, Vincent Vande Vyvre wrote:

Le 04/08/2013 18:06, Jacknaruto a écrit :

Hi, Guys!

I created a thread class based QThread, and defined some signals to 
update UI through main thread.


the UI used a stackedWidget,someone page named 'progressPage' have a 
progressBar and a Label, the next page named 'resultsPage' shows 
results(some Labels).


When the window showed progressPage, my code that updates progressBar 
was well, but the updating resultsPage's labels signals seems ignored 
by main thread.(I guess, because I added some prints in the slot, it 
wasn't printed)


the code like this:

 1. class worker(QtCore.QThread):
 2. sig_jump_finish_page = QtCore.pyqtSignal()
 3. sig_set_label_text = QtCore.pyqtSignal(str, str)
 4. sig_set_progress_value = QtCore.pyqtSignal(int)
5.

 6. for dirpath, dirnames, filenames in os.walk(self.root):
 7. for filename in filenames:
 8. self.sig_set_label_text.emit('current', self.current()) # work well
 9. # so something
10.

11. #self.dialog.set_found(str(self.found())) # work well
12. #self.dialog.set_all(str(self.total())) # work well
13. self.sig_set_label_text.emit('found', str(self.found())) # :(
14. self.sig_set_label_text.emit('all', str(self.total())) # :(
15.

16. self.sig_jump_finish_page.emit()


So I have to update UI directly in the thread(comments Line 11-12 
shows), it looks work well.


I found the difference between line 8 and line 13-14 is line 8 
manipulates current page -progressPage, line 13-14 manipulates next 
page -resultsPage.


Is some wrongs in there?






Have a look at my comments:

class worker(QtCore.QThread):
sig_jump_finish_page = QtCore.pyqtSignal()
sig_set_label_text = QtCore.pyqtSignal(str, str)
sig_set_progress_value = QtCore.pyqtSignal(int)


I'm sorry.
In run() function the code below
for dirpath, dirnames, filenames in os.walk(self.root): # What is 
'self' here ?
self is current object, isn't it? self.root is a path which the 
user will specify.

for filename in filenames:
self.sig_set_label_text.emit('current', self.current()) # where is 
'current' ?

# so something
self.current() is a getter, it just returns a member that shows the 
path of the current work.


#self.dialog.set_found(str(self.found())) # What is self, and dialog, 
and found ?

the main thread is a dialog object.
self.dialog was assigned the dialog object in the __init__ of 
worker class.
self.found() is a getter also, it returns the number of meeting the 
conditions. self.total() means like this.

#self.dialog.set_all(str(self.total())) # ...
self.sig_set_label_text.emit('found', str(self.found())) # again ?
self.sig_set_label_text.emit('all', str(self.total())) # etc

self.sig_jump_finish_page.emit()


dialog.set_all() and so on just sets the widget's text.

My English is poor, I hopeyou will excuse me.

--
http://mail.python.org/mailman/listinfo/python-list


Re: In pyqt, some signals seems not work well

2013-08-04 Thread Vincent Vande Vyvre

Le 04/08/2013 18:06, Jacknaruto a écrit :

Hi, Guys!

I created a thread class based QThread, and defined some signals to 
update UI through main thread.


the UI used a stackedWidget,someone page named 'progressPage' have a 
progressBar and a Label, the next page named 'resultsPage' shows 
results(some Labels).


When the window showed progressPage, my code that updates progressBar 
was well, but the updating resultsPage's labels signals seems ignored 
by main thread.(I guess, because I added some prints in the slot, it 
wasn't printed)


the code like this:

 1. class worker(QtCore.QThread):
 2. sig_jump_finish_page = QtCore.pyqtSignal()
 3. sig_set_label_text = QtCore.pyqtSignal(str, str)
 4. sig_set_progress_value = QtCore.pyqtSignal(int)
5.

 6. for dirpath, dirnames, filenames in os.walk(self.root):
 7. for filename in filenames:
 8. self.sig_set_label_text.emit('current', self.current()) # work well
 9. # so something
10.

11. #self.dialog.set_found(str(self.found())) # work well
12. #self.dialog.set_all(str(self.total())) # work well
13. self.sig_set_label_text.emit('found', str(self.found())) # :(
14. self.sig_set_label_text.emit('all', str(self.total())) # :(
15.

16. self.sig_jump_finish_page.emit()


So I have to update UI directly in the thread(comments Line 11-12 
shows), it looks work well.


I found the difference between line 8 and line 13-14 is line 8 
manipulates current page -progressPage, line 13-14 manipulates next 
page -resultsPage.


Is some wrongs in there?






Have a look at my comments:

class worker(QtCore.QThread):
sig_jump_finish_page = QtCore.pyqtSignal()
sig_set_label_text = QtCore.pyqtSignal(str, str)
sig_set_progress_value = QtCore.pyqtSignal(int)

for dirpath, dirnames, filenames in os.walk(self.root): # What is 'self' 
here ?

for filename in filenames:
self.sig_set_label_text.emit('current', self.current()) # where is 
'current' ?

# so something

#self.dialog.set_found(str(self.found())) # What is self, and dialog, 
and found ?

#self.dialog.set_all(str(self.total())) # ...
self.sig_set_label_text.emit('found', str(self.found())) # again ?
self.sig_set_label_text.emit('all', str(self.total())) # etc

self.sig_jump_finish_page.emit()

--
Vincent V.V.
Oqapy <https://launchpad.net/oqapy> . Qarte 
<https://launchpad.net/qarte> . PaQager <https://launchpad.net/paqager>

--
http://mail.python.org/mailman/listinfo/python-list


In pyqt, some signals seems not work well

2013-08-04 Thread Jacknaruto
Hi, Guys!
I created a thread class based QThread, and defined some signals to update UI 
through main thread.
the UI used a stackedWidget,someone page named 'progressPage' have a 
progressBar and a Label, the next page named 'resultsPage' shows results(some 
Labels).
When the window showed progressPage, my code that updates progressBar was well, 
but the updating resultsPage's labels signals seems ignored by main thread.(I 
guess, because I added some prints in the slot, it wasn't printed)
the code like this:class worker(QtCore.QThread):sig_jump_finish_page = 
QtCore.pyqtSignal()sig_set_label_text = QtCore.pyqtSignal(str,  str)
sig_set_progress_value = QtCore.pyqtSignal(int)
for dirpath,  dirnames, filenames  in os.walk(self.root):for 
filename in filenames:self.sig_set_label_text.emit('current', 
self.current())   # work well# so something
#self.dialog.set_found(str(self.found()))  # work well
#self.dialog.set_all(str(self.total()))  # work well
self.sig_set_label_text.emit('found',  str(self.found()))  # :(
self.sig_set_label_text.emit('all',  str(self.total()))   # :(
self.sig_jump_finish_page.emit()
So I have to update UI directly in the thread(comments Line 11-12 shows), it 
looks work well.
I found the difference between line 8 and line 13-14 is line 8 manipulates 
current page -progressPage, line 13-14 manipulates next page -resultsPage.
Is some wrongs in there?


  -- 
http://mail.python.org/mailman/listinfo/python-list


Why are my signals being ignored?

2011-06-22 Thread Anthony Papillion
Hello Everyone,

So I figured out the last problem about why I couldn't load my UI files but
now I've got something that has be totally stumped. I've worked on it most
of the day yesterday, Google'd it, and fought with it today and I'm
admitting defeat and coming to the group with hat in hand asking for help.

For some reason, in the code below, my signals are being completely ignored.
For example, you'll notice that I connected the 'btnExit' to the method
called 'clickedButton()' but, for some reason, when the button is clicked,
the method is never called. I've been following tutorials and this seems to
be the proper way to wire signals yet mine simply don't work.

Would anyone be so kind as to look over the following code and give me a bit
of advice (or direction) as to what I might be doing wrong?

Thanks!
Anthony

Code:

#!/usr/bin/env python

import sys

try:
import pygtk
 pygtk.require("2.0")
except:
print "Error. PYGTK could not be loaded."
 sys.exit(1)
try:
import gtk
import gtk.glade
except:
print "GTK not present or not loaded."
sys,exit(1)
 class TestClass(object):
 def __init__(self):
 self.uiFile = "MainWindow.glade"
self.wTree = gtk.Builder()
self.wTree.add_from_file(self.uiFile)
 self.window = self.wTree.get_object("winMain")
if self.window:
 self.window.connect("destroy", gtk.main_quit)
 dic = { "on_btnExit_clicked" : self.clickButton, "on_winMain_destroy" :
gtk.main_quit }
 self.wTree.connect_signals(dic)
self.window.show()
else:
 print "Could not load window"
sys.exit(1)
  def clickButton(self, widget):
print "You clicked exit!"
  def exit(self, widget):
 gtk.main_quit()
 def update_file_selection(self, widget, data=None):
 selected_filename = FileChooser.get_filename()
print selected_filename
 if __name__ == "__main__":
Tester = TestClass()
gtk.main()
-- 
http://mail.python.org/mailman/listinfo/python-list


Condition signals and restarts, resumable exceptions (was: Comparison with False - something I don't understand)

2010-12-09 Thread Teemu Likonen
* 2010-12-06 00:14 (-0800), Paul Rubin wrote:

> You know, I've heard the story from language designers several times
> over, that they tried putting resumable exceptions into their
> languages and it turned out to be a big mess, so they went to
> termination exceptions that fixed the issue. Are there any languages
> out there with resumable exceptions?

As some people have pointer out Common Lisp is one of those languages. I
don't know anything about language design, I'm just a hobbyist
programmer, but I think Common Lisp's condition system and its restarts
are straight-forward and easy to understand from programmer's point of
view.

Here's the relevant chapter in Peter Seibel's Practical Common Lisp:

http://www.gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html
-- 
http://mail.python.org/mailman/listinfo/python-list


pyqt signals

2010-09-03 Thread luca72
Hello i have write this but i not able to connect the emit of the
class Socket to the Form class, can you help me?

class Socket(QtNetwork.QTcpSocket):
def __init__(self, parent=None):
super(Socket, self).__init__(parent)
self.connect(self, QtCore.SIGNAL("readyRead()"),
self.leggi_richiesta)

def leggi_richiesta(self):
messaggio = self.readData(self.bytesAvailable())
print 'dati_letti = ', messaggio
self.emit(QtCore.SIGNAL("messaggio"), messaggio)
print 'segnale emesso'

class Form(QWidget, Ui_Form):
"""
Class documentation goes here.
"""
def __init__(self, parent = None):
"""
Constructor
"""

connesso_in_arr =False
self.coda = False
QWidget.__init__(self, parent)
self.setupUi(self)
self.dati = False
self.lu = TcpServer()
self.lu
self.connect(Socket(self), QtCore.SIGNAL('messaggio'),
self.leggo_risposta)


def leggo_risposta(self, messaggio):
self.plainTextEdit_2.appendPlainText(messaggio)

Thanks Luca
-- 
http://mail.python.org/mailman/listinfo/python-list


pyqt unhandled RuntimeError \"no access to protected functions or signals for objects not created from Python

2010-09-03 Thread luca72
Hello i have also write to pyqt mailing list but maybe you can help me
to solve this question:
I have write a tcpserver but wheni try to read by the signal
readyRead() e get the error
this the part of the program:
def nuova_connessione(self):
print 'Nuova connessione'
self.nuovo_socket =
self.mio_server.nextPendingConnection()
print self.nuovo_socket
self.connect(self.nuovo_socket,
QtCore.SIGNAL("connected()"), self.
connessione)
self.connect(self.nuovo_socket,
QtCore.SIGNAL("readyRead()"), self.
leggo_risposta)
self.connect(self.nuovo_socket,
QtCore.SIGNAL("disconnected"), self.
sconnesso)
self.connect(self.nuovo_socket,
QtCore.SIGNAL("error(Qtcore.
QAbsatctSocket::SocketError)"), self.server_errore)

def leggo_risposta(self):
   cosa_leggo = self.nuovo_socket.readData(self.nuovo_socket.
bytesAvailable())
can you help me
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt signals/slots dialogs question

2010-06-07 Thread Thomas Jollans
On 06/07/2010 08:21 PM, AlienBaby wrote:
> On Jun 7, 5:21 pm, AlienBaby  wrote:
>   
>> My real aim here is to learn pyqt, so I would rather not the the
>> QWizard process until I understand myself whats going on behind the
>> scenes.
>> 
> Perhaps I posted to early, but a little more perserverance and I have
> managed to unthaw the brain and move forward.  I've ended up with the
> following. It does what I need, and now it's working I can think
> around how to implement with a better approach;
>   
I haven't done much Qt programming, and all of it in C++, but anyway:

my approach is to subclass QFrame (or, here, QDialog makes sense), and,
in the constructor, set up the UI and call connect(...). In C++, there's
a connect macro -- is there a connect function in QtCore, maybe?
"welcome.ui.welcomeNext.connect(welcome.ui.welcomeNext, ..." doesn't
look right.
>
> from PyQt4 import QtCore, QtGui
> from WELCOME import Ui_Dialog as welcomeDialog
> from SOURCE_TYPE_SELECT import Ui_Dialog as sourceTypeSelectDialog
> from SOURCE_TYPE_CONFIRMATION import Ui_Dialog as
> sourceTypeConfirmationDialog
>
> ..>snip<
>
> class WelcomeDialog(QtGui.QDialog):
> def __init__(self,parent=None):
> QtGui.QWidget.__init__(self,parent)
> self.ui=welcomeDialog()
> self.ui.setupUi(self)
>
> class SourceTypeSelect(QtGui.QDialog):
> def __init__(self,parent=None):
> QtGui.QWidget.__init__(self,parent)
> self.ui=sourceTypeSelectDialog()
> self.ui.setupUi(self)
>
> class SourceTypeConfirmation(QtGui.QDialog):
> def __init__(self,parent=None):
> QtGui.QWidget.__init__(self,parent)
> self.ui=sourceTypeConfirmationDialog()
> self.ui.setupUi(self)
>
>
> def WelcomeNext():
> welcome.hide()
> sourceTypeSelect.show()
> def WelcomeCancel():
> sys.exit()
>
>
> def SourceTypeSelectNext():
> sourceTypeSelect.hide()
> for widget in
> sourceTypeSelect.ui.availableChoices.findChildren(QtGui.QWidget):
> if widget.isChecked():
> print widget.text()
>  
> sourceTypeConfirmation.ui.selectedSourceType.setText(widget.text())
> sourceTypeConfirmation.show()
> def SourceTypeSelectCancel():
> sys.exit()
>
>
> def SourceTypeConfirmationBack():
> sourceTypeConfirmation.hide()
> sourceTypeSelect.show()
>
>
> if __name__ == "__main__":
> app = QtGui.QApplication(sys.argv)
>
> #Instance dialogs and connect buttons
> welcome=WelcomeDialog()
>  
> welcome.ui.welcomeNext.connect(welcome.ui.welcomeNext,QtCore.SIGNAL("clicked()"),WelcomeNext)
>  
> welcome.ui.welcomeCancel.connect(welcome.ui.welcomeCancel,QtCore.SIGNAL("clicked()"),WelcomeCancel)
>
>
> sourceTypeSelect=SourceTypeSelect()
>  
> sourceTypeSelect.ui.sourceTypeSelectNext.connect(sourceTypeSelect.ui.sourceTypeSelectNext,QtCore.SIGNAL("clicked()"),SourceTypeSelectNext)
>  
> sourceTypeSelect.ui.sourceTypeSelectCancel.connect(sourceTypeSelect.ui.sourceTypeSelectCancel,QtCore.SIGNAL("clicked()"),SourceTypeSelectCancel)
>
>
> sourceTypeConfirmation=SourceTypeConfirmation()
>  
> sourceTypeConfirmation.ui.sourceTypeConfirmationBack.connect(sourceTypeConfirmation.ui.sourceTypeConfirmationBack,QtCore.SIGNAL("clicked()"),SourceTypeConfirmationBack)
>
>
> welcome.show()
> sys.exit(app.exec_())
>
>
>
>
>   

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt signals/slots dialogs question

2010-06-07 Thread AlienBaby
On Jun 7, 5:21 pm, AlienBaby  wrote:
> My real aim here is to learn pyqt, so I would rather not the the
> QWizard process until I understand myself whats going on behind the
> scenes.

Perhaps I posted to early, but a little more perserverance and I have
managed to unthaw the brain and move forward.  I've ended up with the
following. It does what I need, and now it's working I can think
around how to implement with a better approach;


from PyQt4 import QtCore, QtGui
from WELCOME import Ui_Dialog as welcomeDialog
from SOURCE_TYPE_SELECT import Ui_Dialog as sourceTypeSelectDialog
from SOURCE_TYPE_CONFIRMATION import Ui_Dialog as
sourceTypeConfirmationDialog

..>snip<

class WelcomeDialog(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui=welcomeDialog()
self.ui.setupUi(self)

class SourceTypeSelect(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui=sourceTypeSelectDialog()
self.ui.setupUi(self)

class SourceTypeConfirmation(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui=sourceTypeConfirmationDialog()
self.ui.setupUi(self)


def WelcomeNext():
welcome.hide()
sourceTypeSelect.show()
def WelcomeCancel():
sys.exit()


def SourceTypeSelectNext():
sourceTypeSelect.hide()
for widget in
sourceTypeSelect.ui.availableChoices.findChildren(QtGui.QWidget):
if widget.isChecked():
print widget.text()
 
sourceTypeConfirmation.ui.selectedSourceType.setText(widget.text())
sourceTypeConfirmation.show()
def SourceTypeSelectCancel():
sys.exit()


def SourceTypeConfirmationBack():
sourceTypeConfirmation.hide()
sourceTypeSelect.show()


if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)

#Instance dialogs and connect buttons
welcome=WelcomeDialog()
 
welcome.ui.welcomeNext.connect(welcome.ui.welcomeNext,QtCore.SIGNAL("clicked()"),WelcomeNext)
 
welcome.ui.welcomeCancel.connect(welcome.ui.welcomeCancel,QtCore.SIGNAL("clicked()"),WelcomeCancel)


sourceTypeSelect=SourceTypeSelect()
 
sourceTypeSelect.ui.sourceTypeSelectNext.connect(sourceTypeSelect.ui.sourceTypeSelectNext,QtCore.SIGNAL("clicked()"),SourceTypeSelectNext)
 
sourceTypeSelect.ui.sourceTypeSelectCancel.connect(sourceTypeSelect.ui.sourceTypeSelectCancel,QtCore.SIGNAL("clicked()"),SourceTypeSelectCancel)


sourceTypeConfirmation=SourceTypeConfirmation()
 
sourceTypeConfirmation.ui.sourceTypeConfirmationBack.connect(sourceTypeConfirmation.ui.sourceTypeConfirmationBack,QtCore.SIGNAL("clicked()"),SourceTypeConfirmationBack)


welcome.show()
sys.exit(app.exec_())




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt signals/slots dialogs question

2010-06-07 Thread AlienBaby
My real aim here is to learn pyqt, so I would rather not the the
QWizard process until I understand myself whats going on behind the
scenes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt signals/slots dialogs question

2010-06-07 Thread AlienBaby
On Jun 7, 4:37 pm, Phil Thompson  wrote:
> On Mon, 7 Jun 2010 08:22:07 -0700 (PDT), AlienBaby
> 
> wrote:
>
>
>
>
>
> > Hi,
>
> > I'm just starting to get to grips with PyQt, and I'm having a bit of
> > trouble connecting slots / signals, or understanding how I should do
> > so to achieve what I am after.
>
> > I am trying to write an application that will display a sequence of
> > dialogs, with back / next / cancel buttons to step through the
> > dialogs. Each dialog will capture user input, ask the user to browse
> > for a file, present some radio-buttons for a selection etc..
>
> > I've put the dialogs together in Designer, and I come to startup the
> > app with a small piece of python code, create an instance of each
> > dialog, and then connect up the buttons to any methods needed to
> > control the movement through the dialogs etc.
>
> > I'm having a brain-freeze though, and just can't figure out what I
> > should be doing next, or the best approach to take.
>
> > for example, Currently I am thinking I would need to connect the
> > clicked() signal of the Next button on dialog 1 to a method say,
> > 'dialog1Next' that would then hide dialog1 and show dialog2.  I would
> > then need to connect Dialog 2's clicked() signal of its next button to
> > a method called 'dialog2Next' that hides dialog2 and shows dialog3
> > etc...
>
> > I would also, for example,  need methods for dialog2Back,
> > dialog2cancel, dialog1cancel etc..
>
> > I'm having trouble figuring out how to setup the connections, and
> > where the slot-methods should live..
>
> > I have this so far;
>
> > from PyQt4 import QtCore, QtGui
> > from WELCOME import Ui_Dialog as welcomeDialog
> > from SOURCE_TYPE_SELECT import Ui_Dialog as sourceTypeSelectDialog
> > from SOURCE_TYPE_CONFIRMATION import Ui_Dialog as
> > sourceTypeConfirmationDialog
> > from ACCEPT_EULA import Ui_Dialog as acceptEulaDialog
> > from CONFIRM_REQUIREMENTS import Ui_Dialog as
> > confirmRequirementsDialog
> > from SOURCE_BINARY_LOCATE import Ui_Dialog as sourceBinaryLocateDialog
> > from SOURCE_BINARY_PROBLEMS import Ui_Dialog as
> > sourceBinaryProblemsDialog
> > from OUTFILE_LOCATE import Ui_Dialog as outfileLocateDialog
> > from OUTFILE_PROBLEMS import Ui_Dialog as outfileProblemsDialog
> > from COLLECTION_PROGRESS import Ui_Dialog as collectionProgressDialog
> > from OUTFILE_LOCATION import Ui_Dialog as outfileLocationDialog
>
> > class StartQT4(QtGui.QDialog):
> >     def __init__(self, parent=None):
> >         QtGui.QWidget.__init__(self, parent)
> >         self.Welcome = welcomeDialog()
> >         self.Welcome.setupUi(self)
> >         self.SourceTypeSelect = sourceTypeSelectDialog()
> >         self.SourceTypeConfirmation = sourceTypeConfirmationDialog()
> >         self.AcceptEula = acceptEulaDialog()
> >         self.ConfirmRequirements=confirmRequirementsDialog()
> >         self.SourceBinaryLocate=sourceBinaryLocateDialog()
> >         self.SourceBinaryProblems=sourceBinaryProblemsDialog()
> >         self.OutfileLocate=outfileLocateDialog()
> >         self.OutfileProbelms=outfileProblemsDialog()
> >         self.CollectionProgress=collectionProgressDialog()
> >         self.OutfileLocation=outfileLocationDialog
>
> >         #Connect up next/back/cancel etc.. buttons
>
> > ???     self.Welcome.connect(self.Welcome.welcomeNext,
> > QtCore.SIGNAL("clicked()"),WelcomeNext)
>
> > def WelcomeNext():
> >         #Code here to hide Welcome dialog and show SourceTypeSelect
> > dialog
>
> > if __name__ == "__main__":
> >    app = QtGui.QApplication(sys.argv)
> >    myapp = StartQT4()
> >    myapp.show()
> >    sys.exit(app.exec_())
>
> > My questions are, am I approaching this the right way, with a method
> > per action per dialog to move through the dialogs, and just how do I
> > setup the connections I need. I'm getting confused with scope etc. IE:
> > if the connect is right, and WelcomeNext fires, how can it refer to
> > myapp.SourceTypeSelect.show() or myapp.Welcome.hide()
>
> > Any help much appreciated.
>
> Sounds like you are trying to build a wizard the hard way.
>
> Use Designer to create a QWizard with the contents of each of your dialogs
> as a QWizardPage.
>
> Phil- Hide quoted text -
>
> - Show quoted text -

Interesting idea. I shall take a look, but there is q fair amount of
work that needs to be done between dialogs, validation and other
thoings etc..  Would a QWizard help?


As well, I would like to understand the process of coding my own so I
can build other UI's also.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt signals/slots dialogs question

2010-06-07 Thread AlienBaby
I've made a little progress;

This appears to setup a connection that fires when the welcomeNext
button in the Welcome dialog is clicked;

self.Welcome.welcomeNext.connect(self.Welcome.welcomeNext,QtCore.SIGNAL("clicked()"),self.WelcomeNext)


In the StartQT4 class I now have the WelcomeNext method;

def WelcomeNext(self):
self.Welcome.setVisible(False)
self.SourceTypeSelect.setVisible(True)

Though I am now getting

AttributeError: 'Ui_Dialog' object has no attribute 'setVisible'

Which, is right. Because it's not really a QDialog class.

Instead of using a 'WelcomeNext' method as the slot, should I just
connect the clicked() signal to both the hide slot of the welcome
dialog and the show slot of the SourceTypeSelect dialog?  .. though
then where would any code I wanted to run say, (for the sake of
argument) between the hiding of one dialog and the showing of the
next?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt signals/slots dialogs question

2010-06-07 Thread Phil Thompson
On Mon, 7 Jun 2010 08:22:07 -0700 (PDT), AlienBaby

wrote:
> Hi,
> 
> I'm just starting to get to grips with PyQt, and I'm having a bit of
> trouble connecting slots / signals, or understanding how I should do
> so to achieve what I am after.
> 
> I am trying to write an application that will display a sequence of
> dialogs, with back / next / cancel buttons to step through the
> dialogs. Each dialog will capture user input, ask the user to browse
> for a file, present some radio-buttons for a selection etc..
> 
> I've put the dialogs together in Designer, and I come to startup the
> app with a small piece of python code, create an instance of each
> dialog, and then connect up the buttons to any methods needed to
> control the movement through the dialogs etc.
> 
> I'm having a brain-freeze though, and just can't figure out what I
> should be doing next, or the best approach to take.
> 
> for example, Currently I am thinking I would need to connect the
> clicked() signal of the Next button on dialog 1 to a method say,
> 'dialog1Next' that would then hide dialog1 and show dialog2.  I would
> then need to connect Dialog 2's clicked() signal of its next button to
> a method called 'dialog2Next' that hides dialog2 and shows dialog3
> etc...
> 
> I would also, for example,  need methods for dialog2Back,
> dialog2cancel, dialog1cancel etc..
> 
> I'm having trouble figuring out how to setup the connections, and
> where the slot-methods should live..
> 
> I have this so far;
> 
> from PyQt4 import QtCore, QtGui
> from WELCOME import Ui_Dialog as welcomeDialog
> from SOURCE_TYPE_SELECT import Ui_Dialog as sourceTypeSelectDialog
> from SOURCE_TYPE_CONFIRMATION import Ui_Dialog as
> sourceTypeConfirmationDialog
> from ACCEPT_EULA import Ui_Dialog as acceptEulaDialog
> from CONFIRM_REQUIREMENTS import Ui_Dialog as
> confirmRequirementsDialog
> from SOURCE_BINARY_LOCATE import Ui_Dialog as sourceBinaryLocateDialog
> from SOURCE_BINARY_PROBLEMS import Ui_Dialog as
> sourceBinaryProblemsDialog
> from OUTFILE_LOCATE import Ui_Dialog as outfileLocateDialog
> from OUTFILE_PROBLEMS import Ui_Dialog as outfileProblemsDialog
> from COLLECTION_PROGRESS import Ui_Dialog as collectionProgressDialog
> from OUTFILE_LOCATION import Ui_Dialog as outfileLocationDialog
> 
> 
> 
> class StartQT4(QtGui.QDialog):
> def __init__(self, parent=None):
> QtGui.QWidget.__init__(self, parent)
> self.Welcome = welcomeDialog()
> self.Welcome.setupUi(self)
> self.SourceTypeSelect = sourceTypeSelectDialog()
> self.SourceTypeConfirmation = sourceTypeConfirmationDialog()
> self.AcceptEula = acceptEulaDialog()
> self.ConfirmRequirements=confirmRequirementsDialog()
> self.SourceBinaryLocate=sourceBinaryLocateDialog()
> self.SourceBinaryProblems=sourceBinaryProblemsDialog()
> self.OutfileLocate=outfileLocateDialog()
> self.OutfileProbelms=outfileProblemsDialog()
> self.CollectionProgress=collectionProgressDialog()
> self.OutfileLocation=outfileLocationDialog
> 
> #Connect up next/back/cancel etc.. buttons
> 
> ??? self.Welcome.connect(self.Welcome.welcomeNext,
> QtCore.SIGNAL("clicked()"),WelcomeNext)
> 
> 
> 
> def WelcomeNext():
> #Code here to hide Welcome dialog and show SourceTypeSelect
> dialog
> 
> 
> 
> if __name__ == "__main__":
>   app = QtGui.QApplication(sys.argv)
>   myapp = StartQT4()
>   myapp.show()
>   sys.exit(app.exec_())
> 
> 
> 
> 
> 
> My questions are, am I approaching this the right way, with a method
> per action per dialog to move through the dialogs, and just how do I
> setup the connections I need. I'm getting confused with scope etc. IE:
> if the connect is right, and WelcomeNext fires, how can it refer to
> myapp.SourceTypeSelect.show() or myapp.Welcome.hide()
> 
> 
> Any help much appreciated.

Sounds like you are trying to build a wizard the hard way.

Use Designer to create a QWizard with the contents of each of your dialogs
as a QWizardPage.

Phil
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQt signals/slots dialogs question

2010-06-07 Thread AlienBaby
Hi,

I'm just starting to get to grips with PyQt, and I'm having a bit of
trouble connecting slots / signals, or understanding how I should do
so to achieve what I am after.

I am trying to write an application that will display a sequence of
dialogs, with back / next / cancel buttons to step through the
dialogs. Each dialog will capture user input, ask the user to browse
for a file, present some radio-buttons for a selection etc..

I've put the dialogs together in Designer, and I come to startup the
app with a small piece of python code, create an instance of each
dialog, and then connect up the buttons to any methods needed to
control the movement through the dialogs etc.

I'm having a brain-freeze though, and just can't figure out what I
should be doing next, or the best approach to take.

for example, Currently I am thinking I would need to connect the
clicked() signal of the Next button on dialog 1 to a method say,
'dialog1Next' that would then hide dialog1 and show dialog2.  I would
then need to connect Dialog 2's clicked() signal of its next button to
a method called 'dialog2Next' that hides dialog2 and shows dialog3
etc...

I would also, for example,  need methods for dialog2Back,
dialog2cancel, dialog1cancel etc..

I'm having trouble figuring out how to setup the connections, and
where the slot-methods should live..

I have this so far;

from PyQt4 import QtCore, QtGui
from WELCOME import Ui_Dialog as welcomeDialog
from SOURCE_TYPE_SELECT import Ui_Dialog as sourceTypeSelectDialog
from SOURCE_TYPE_CONFIRMATION import Ui_Dialog as
sourceTypeConfirmationDialog
from ACCEPT_EULA import Ui_Dialog as acceptEulaDialog
from CONFIRM_REQUIREMENTS import Ui_Dialog as
confirmRequirementsDialog
from SOURCE_BINARY_LOCATE import Ui_Dialog as sourceBinaryLocateDialog
from SOURCE_BINARY_PROBLEMS import Ui_Dialog as
sourceBinaryProblemsDialog
from OUTFILE_LOCATE import Ui_Dialog as outfileLocateDialog
from OUTFILE_PROBLEMS import Ui_Dialog as outfileProblemsDialog
from COLLECTION_PROGRESS import Ui_Dialog as collectionProgressDialog
from OUTFILE_LOCATION import Ui_Dialog as outfileLocationDialog



class StartQT4(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.Welcome = welcomeDialog()
self.Welcome.setupUi(self)
self.SourceTypeSelect = sourceTypeSelectDialog()
self.SourceTypeConfirmation = sourceTypeConfirmationDialog()
self.AcceptEula = acceptEulaDialog()
self.ConfirmRequirements=confirmRequirementsDialog()
self.SourceBinaryLocate=sourceBinaryLocateDialog()
self.SourceBinaryProblems=sourceBinaryProblemsDialog()
self.OutfileLocate=outfileLocateDialog()
self.OutfileProbelms=outfileProblemsDialog()
self.CollectionProgress=collectionProgressDialog()
self.OutfileLocation=outfileLocationDialog

#Connect up next/back/cancel etc.. buttons

??? self.Welcome.connect(self.Welcome.welcomeNext,
QtCore.SIGNAL("clicked()"),WelcomeNext)



def WelcomeNext():
#Code here to hide Welcome dialog and show SourceTypeSelect
dialog



if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())





My questions are, am I approaching this the right way, with a method
per action per dialog to move through the dialogs, and just how do I
setup the connections I need. I'm getting confused with scope etc. IE:
if the connect is right, and WelcomeNext fires, how can it refer to
myapp.SourceTypeSelect.show() or myapp.Welcome.hide()


Any help much appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fcntl, serial ports and serial signals on RS232.

2010-04-09 Thread Max Kotasek
On Apr 8, 11:17 am, Grant Edwards  wrote:
> On 2010-04-07, Max Kotasek  wrote:
>
> > I'm trying to figure out how to parse the responses fromfcntl.ioctl()
> > calls that modify the serial lines in a way that asserts that the line
> > is now changed.
>
> Two comments:
>
>   1) None of the Linux serial drivers I've worked on return line states
>      except when you call TIOCMGET.
>
>   2) If the TIOCMBI[S|C] call returned a 'success' value, then the
>      line was set to what you requested.
>
> If you want to read back the state that you just wrote, you can call
> TIOCMGET, but for the "output" pins it's always going to return the
> last value that was written.
>
> > For example I may want to drop RTS explicitly, and
> > assert that the line has been dropped before returning.
>
> Call TIOCMSET.  If it doesn't return an error, then you're done.
>
> > Here is a brief snippet of code that I've been using to do that, but
> > not sure what to do with the returned response:
>
> What returned response?
>
> The only thing that is returned by TIOCMBIS/TIOCMBIC is a status value
> of 0 for success and <0 for failure. IIRC, that value is checked by
> Python'sfcntl.ioctl wrapper and it will raise an exception on
> failure.
>
> > Is someone familiar with manipulating serial signals like this in
> > python?
>
> Yes.
>
> > Am I even taking the right approach by using thefcntl.ioctl call?
>
> Yes.  When you set/clear RTS or DTR do they not go up/down?
>
> Even if you can't use pyserial, it's a good source for example code.
>
> --
> Grant Edwards               grant.b.edwards        Yow! TONY RANDALL!  Is YOUR
>                                   at               life a PATIO of FUN??
>                               gmail.com            


I appreciate the feedback.  I'm working in an environment with a lot
of changing factors, it's nice to have a piece not act unexpectedly.

Max

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fcntl, serial ports and serial signals on RS232.

2010-04-08 Thread Grant Edwards
On 2010-04-08, Anssi Saari  wrote:

> It seems to me also that RTS is always on after the port has been
> opened. I didn't dig out my voltmeter or anything to check this,
> though.

IIRC, that's generally true: RTS and DTR are both set to "on" by the
tty layer's open() handler _if_ the device's useage count was 0.  If
you open an already open port, then the RTS and DTR lines are left
alone.

-- 
Grant Edwards   grant.b.edwardsYow! Someone in DAYTON,
  at   Ohio is selling USED
  gmail.comCARPETS to a SERBO-CROATIAN
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fcntl, serial ports and serial signals on RS232.

2010-04-08 Thread Grant Edwards
On 2010-04-07, Max Kotasek  wrote:

> I'm trying to figure out how to parse the responses from fcntl.ioctl()
> calls that modify the serial lines in a way that asserts that the line
> is now changed.

Two comments:

  1) None of the Linux serial drivers I've worked on return line states
 except when you call TIOCMGET.

  2) If the TIOCMBI[S|C] call returned a 'success' value, then the
 line was set to what you requested.

If you want to read back the state that you just wrote, you can call
TIOCMGET, but for the "output" pins it's always going to return the 
last value that was written.

> For example I may want to drop RTS explicitly, and
> assert that the line has been dropped before returning.

Call TIOCMSET.  If it doesn't return an error, then you're done.

> Here is a brief snippet of code that I've been using to do that, but
> not sure what to do with the returned response:

What returned response?

The only thing that is returned by TIOCMBIS/TIOCMBIC is a status value
of 0 for success and <0 for failure. IIRC, that value is checked by
Python's fcntl.ioctl wrapper and it will raise an exception on
failure.

> Is someone familiar with manipulating serial signals like this in
> python?

Yes.

> Am I even taking the right approach by using the fcntl.ioctl call?

Yes.  When you set/clear RTS or DTR do they not go up/down?

Even if you can't use pyserial, it's a good source for example code.

-- 
Grant Edwards   grant.b.edwardsYow! TONY RANDALL!  Is YOUR
  at   life a PATIO of FUN??
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fcntl, serial ports and serial signals on RS232.

2010-04-08 Thread Anssi Saari
Max Kotasek  writes:

> Hello to all out there,
>
> I'm trying to figure out how to parse the responses from fcntl.ioctl()
> calls that modify the serial lines in a way that asserts that the line
> is now changed.  For example I may want to drop RTS explicitly, and
> assert that the line has been dropped before returning.
>
> Here is a brief snippet of code that I've been using to do that, but
> not sure what to do with the returned response:
>
> def set_RTS(self, state=True):
>   if self.fd is None:
> return 0
>
>   p = struct.pack('I', termios.TIOCM_RTS)
>   if state:
> return fcntl.ioctl(self.fd, termios.TIOCMBIS, p)
>   else:
> return fcntl.ioctl(self.fd, termios.TIOCMBIC, p)
>
> The problem is I get responses like '\x01\x00\x00\x00', or
> '\x02\x00\x00\x00'  and I'm not sure what they mean.

I'm not an expert in this by any means. However, I don't think that
fcntl call actually returns the port status after the bit setting. But
why not check it explicitly with termios.TIOCMGET? At least then I
seem to be able to toggle the RTS bit (bit 2) in the register. Here
are the trivial functions I used:

def set_rts(fd):
print "Setting RTS."
p = struct.pack('I', termios.TIOCM_RTS) 
fcntl.ioctl(fd, termios.TIOCMBIS, p)

def clear_rts(fd):
print "Clearing RTS."
p = struct.pack('I', termios.TIOCM_RTS) 
fcntl.ioctl(fd, termios.TIOCMBIC, p)

def get_status(fd):
print "Querying RTS state."
stat = struct.pack('I', 0)
rc = fcntl.ioctl(fd, termios.TIOCMGET, stat)
if struct.unpack('I', rc)[0] & termios.TIOCM_RTS:
print "RTS bit is on."
else:
print "RTS bit is off."


It seems to me also that RTS is always on after the port has been
opened. I didn't dig out my voltmeter or anything to check this,
though.
-- 
http://mail.python.org/mailman/listinfo/python-list


fcntl, serial ports and serial signals on RS232.

2010-04-07 Thread Max Kotasek
Hello to all out there,

I'm trying to figure out how to parse the responses from fcntl.ioctl()
calls that modify the serial lines in a way that asserts that the line
is now changed.  For example I may want to drop RTS explicitly, and
assert that the line has been dropped before returning.

Here is a brief snippet of code that I've been using to do that, but
not sure what to do with the returned response:

def set_RTS(self, state=True):
  if self.fd is None:
return 0

  p = struct.pack('I', termios.TIOCM_RTS)
  if state:
return fcntl.ioctl(self.fd, termios.TIOCMBIS, p)
  else:
return fcntl.ioctl(self.fd, termios.TIOCMBIC, p)

The problem is I get responses like '\x01\x00\x00\x00', or
'\x02\x00\x00\x00'  and I'm not sure what they mean.  I tried doing
illogical things like settings CTS using the TIOCM_CTS flag and I end
up just getting back a slightly different binary packed 32 bit integer
(in that case '\x20\x00\x00\x00').  The above example has self.fd
being defined as os.open('/dev/ttyS0', os.O_RDWR | os.O_NONBLOCK).

Is someone familiar with manipulating serial signals like this in
python?  Am I even taking the right approach by using the fcntl.ioctl
call?  The environment is a ubuntu 8.04 distribution.  Unfortunately
due to other limitations, I can't use/extend pyserial, though I would
like to.

I appreciate any advice on this matter,
Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading and signals - main thread solely responsible for signal handling?

2010-02-13 Thread Cameron Simpson
On 13Feb2010 17:22, exar...@twistedmatrix.com  wrote:
| On 04:43 pm, malig...@gmail.com wrote:
| >The main part of my script is a function that does many long reads
| >(urlopen, it's looped). Since I'm hell-bent on employing SIGINFO to
| >display some stats, I needed to run foo() as a seperate thread to
| >avoid getting errno 4 (interrupted system call) errors (which occur if
| >SIGINFO is received while urlopen is setting itself up/waiting for a
| >response). This does the job, SIGINFO is handled without ever brutally
| >interrupting urlopen.
| >
| >The problem is that after starting foo as a thread, my main thread has
| >nothing left to do - unless it receives a signal, and I am forced to
| >keep it in some sort of loop so that ANY signal handling can still
| >occur. I thought I'd just occupy it with a simple while 1: pass loop
| >but that, unfortunately, means 100% CPU usage.
[...]
| 
| MRAB suggested you time.sleep() in a loop, which is probably fine.
| However, if you want to have even /less/ activity than that in the
| main thread, take a look at signal.pause().

Funnily enough I coded this issue just a few weeks ago, and my main
program looks like this:

  def main(argv):
xit = 0
cmd = os.path.basename(argv[0])
SM = SystemManager()
[...set up a bunch of subsystems...]
SM.startAll()
try:
  signal.pause()
except KeyboardInterrupt:
  warn("KeyboardInterrupt interrupts pause()")
  xit = 1
SM.close()
SM.join()
return xit

So SM.close() tells all the subsystems to close and finish up.  That largely
involved putting the "EOF" sentinel value on a lot of Queues, causes the
subsystems to cease processing stuff.  The separate SM.join() does the actaul
waiting for everything.

This makes for clean and timely shutdown for me.
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

If your new theorem can be stated with great simplicity, then there
will exist a pathological exception.- Adrian Mathesis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading and signals - main thread solely responsible for signal handling?

2010-02-13 Thread exarkun

On 04:43 pm, malig...@gmail.com wrote:

The main part of my script is a function that does many long reads
(urlopen, it's looped). Since I'm hell-bent on employing SIGINFO to
display some stats, I needed to run foo() as a seperate thread to
avoid getting errno 4 (interrupted system call) errors (which occur if
SIGINFO is received while urlopen is setting itself up/waiting for a
response). This does the job, SIGINFO is handled without ever brutally
interrupting urlopen.

The problem is that after starting foo as a thread, my main thread has
nothing left to do - unless it receives a signal, and I am forced to
keep it in some sort of loop so that ANY signal handling can still
occur. I thought I'd just occupy it with a simple while 1: pass loop
but that, unfortunately, means 100% CPU usage.

Is there any way I could put the main thread to sleep? Or perhaps my
approach is totally wrong?


I don't think those two options are mutually exclusive. ;)

MRAB suggested you time.sleep() in a loop, which is probably fine. 
However, if you want to have even /less/ activity than that in the main 
thread, take a look at signal.pause().


Also, perhaps not terribly interesting, signal.siginterrupt() was 
recently introduced, which will let you avoid EINTR if SIGINFO is 
received while urlopen is in a syscall (but will also prevent the signal 
from being handled until the syscall returns on its own).


And there's always Twisted & friends. :)

Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading and signals - main thread solely responsible for signal handling?

2010-02-13 Thread MRAB

Maligree wrote:

The main part of my script is a function that does many long reads
(urlopen, it's looped). Since I'm hell-bent on employing SIGINFO to
display some stats, I needed to run foo() as a seperate thread to
avoid getting errno 4 (interrupted system call) errors (which occur if
SIGINFO is received while urlopen is setting itself up/waiting for a
response). This does the job, SIGINFO is handled without ever brutally
interrupting urlopen.

The problem is that after starting foo as a thread, my main thread has
nothing left to do - unless it receives a signal, and I am forced to
keep it in some sort of loop so that ANY signal handling can still
occur. I thought I'd just occupy it with a simple while 1: pass loop
but that, unfortunately, means 100% CPU usage.

Is there any way I could put the main thread to sleep? Or perhaps my
approach is totally wrong?


The simplest fix is to call time.sleep(seconds) in the loop. Repeated
sleeps of 1 second, for example, consume very little CPU time.
--
http://mail.python.org/mailman/listinfo/python-list


threading and signals - main thread solely responsible for signal handling?

2010-02-13 Thread Maligree
The main part of my script is a function that does many long reads
(urlopen, it's looped). Since I'm hell-bent on employing SIGINFO to
display some stats, I needed to run foo() as a seperate thread to
avoid getting errno 4 (interrupted system call) errors (which occur if
SIGINFO is received while urlopen is setting itself up/waiting for a
response). This does the job, SIGINFO is handled without ever brutally
interrupting urlopen.

The problem is that after starting foo as a thread, my main thread has
nothing left to do - unless it receives a signal, and I am forced to
keep it in some sort of loop so that ANY signal handling can still
occur. I thought I'd just occupy it with a simple while 1: pass loop
but that, unfortunately, means 100% CPU usage.

Is there any way I could put the main thread to sleep? Or perhaps my
approach is totally wrong?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt Signals and multiple sources

2009-12-20 Thread Zabin
On Dec 21, 11:15 am, "John Posner"  wrote:
> On Sun, 20 Dec 2009 16:59:11 -0500, Zabin  wrote:
> > I am beginner in programming in pyqt. I have been trying to call the
> > same function from multiple events- but each event results in a
> > different instance of the function. I am just unable to figure out how
> > to retrieve the source which calls the function:
>
> > My source signal declarations are as below:
> > QtCore.QObject.connect(self.ui.Button_Process, QtCore.SIGNAL("clicked
> > ()"), self.activate_tab)
> > QtCore.QObject.connect(self.ui.Button_Material, QtCore.SIGNAL("clicked
> > ()"), self.activate_tab)
> > QtCore.QObject.connect(self.ui.Button_Geometry, QtCore.SIGNAL("clicked
> > ()"), self.activate_tab)
>
> > for each of the above source i want to activate a different instance
> > of the activate_tab function. Any help would be greatly appreciated!
>
> In the self.activate_tab() method, use self.sender() to determine which  
> object sent the signal.
>
> -John- Hide quoted text -
>
> - Show quoted text -

Awesum. That works!

To get the object name you just need to use self.sender().objectName()

Cheers!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt Signals and multiple sources

2009-12-20 Thread John Posner

On Sun, 20 Dec 2009 16:59:11 -0500, Zabin  wrote:


I am beginner in programming in pyqt. I have been trying to call the
same function from multiple events- but each event results in a
different instance of the function. I am just unable to figure out how
to retrieve the source which calls the function:

My source signal declarations are as below:
QtCore.QObject.connect(self.ui.Button_Process, QtCore.SIGNAL("clicked
()"), self.activate_tab)
QtCore.QObject.connect(self.ui.Button_Material, QtCore.SIGNAL("clicked
()"), self.activate_tab)
QtCore.QObject.connect(self.ui.Button_Geometry, QtCore.SIGNAL("clicked
()"), self.activate_tab)

for each of the above source i want to activate a different instance
of the activate_tab function. Any help would be greatly appreciated!


In the self.activate_tab() method, use self.sender() to determine which  
object sent the signal.


-John
--
http://mail.python.org/mailman/listinfo/python-list


PyQt Signals and multiple sources

2009-12-20 Thread Zabin
I am beginner in programming in pyqt. I have been trying to call the
same function from multiple events- but each event results in a
different instance of the function. I am just unable to figure out how
to retrieve the source which calls the function:

My source signal declarations are as below:
QtCore.QObject.connect(self.ui.Button_Process, QtCore.SIGNAL("clicked
()"), self.activate_tab)
QtCore.QObject.connect(self.ui.Button_Material, QtCore.SIGNAL("clicked
()"), self.activate_tab)
QtCore.QObject.connect(self.ui.Button_Geometry, QtCore.SIGNAL("clicked
()"), self.activate_tab)

for each of the above source i want to activate a different instance
of the activate_tab function. Any help would be greatly appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Win32 trouble with threading, signals, and sleep()

2008-08-09 Thread Tim Golden

Lowell Alleman wrote:

I'm running into this issue on Windows with the follow exception at
the time when the signal handler is called:

Traceback (most recent call last):
   ...
self.done.wait(30)
  File "D:\Python24\lib\threading.py", line 348, in wait
self.__cond.wait(timeout)
  File "D:\Python24\lib\threading.py", line 222, in wait
_sleep(delay)
IOError: [Errno 4] Interrupted function call



Well you've certainly picked a ticklish area to run
into problems with ;). First, forget about the
threading aspects for the moment. AFAICT the smallest
program which reproduces your problem is:


import signal
import time

def handler (*args):
  pass

signal.signal(signal.SIGBREAK, handler)
time.sleep (10)



Now run that and do a ctrl-break somewhere in
that time.sleep. Sure enough...


Traceback (most recent call last):
  File "C:\data\temp\sig3.py", line 8, in 
time.sleep (10)
IOError: [Errno 4] Interrupted function call



Under the covers, the sleep function is implemented
as a WaitForSingleObject call with a timeout. The
object being waited on is an anonymous event which
is set from a console ctrl handler when one of
those interrupts happens (ctrl-c / ctrl-break /
shutdown). This makes sure that the (otherwise
blocking) sleep can be interrupted. Something
like this:


import win32api
import win32event

hEvent = win32event.CreateEvent (None, 1, 0, None)
def handler (*args):
  win32event.PulseEvent (hEvent)
  return True

win32api.SetConsoleCtrlHandler (handler, 1)
#
# This line is basically the sleep happening
#
win32event.WaitForSingleObject (hEvent, 1)



For reasons which I'm not aware of, the code
recognises that the interrupt has fired and
sets the WSAEINTR error code, which is the
IOError 4 which you're seeing, and then exits.
EINTR is usually issued when a blocking call
is cancelled explicitly, so presumably this
is considered a simulation of that. Not sure.

What happens now is that control passes
back out to the routine which called the
sleep. But... an exception condition has
been set inside the sleep call and is now
raised, appearing to come from within the
routine which called sleep.

Clear?

You could obviously continue to catch the
exception. Alternatively,
I think your best bet, as long as you can make
it work with the threads, is to install your
own console ctrl handler. Note that the docs
for this specify that:

"When the signal is received, the system creates
a new thread in the process to execute the function."

So you'll need to be quite careful to make your
code thread-safe. But it should work. I adapted
your example slightly to replace all of the lines
setting the signal handlers to one statement:

win32api.SetConsoleCtrlHandler (handler, 1)

and the handler function itself takes only one
arg, the signal no, and returns False to indicate
that control should pass to the next handler, which
will probably be the default Python handler:

def handler(arg):
print "Signal handler", arg
global workers
for w in workers:
w.stop()
return False


Hope that all helps.

TJG

--
http://mail.python.org/mailman/listinfo/python-list


Win32 trouble with threading, signals, and sleep()

2008-08-08 Thread Lowell Alleman
I'm trying to track down an issue with a multi-threaded program that
is responsible for handling real-time monitoring a business process.
Different threads track various aspects of the process and all of the
statistics filter back to the main thread for analysis.  The program
is run as a scheduled task, and various stats are shown in the console
window ("dos box") as it runs.  Normally the main thread tells the
worker threads to stop (using an Event()) when the work is done.

I just recently added some signal handlers to the program to send out
an email if someone comes along and closes the console window. (BTW,
sometimes closing the app is legitimate, so I don't want to just
disable it or run the process in the background)

I'm running into this issue on Windows with the follow exception at
the time when the signal handler is called:

Traceback (most recent call last):
   ...
self.done.wait(30)
  File "D:\Python24\lib\threading.py", line 348, in wait
self.__cond.wait(timeout)
  File "D:\Python24\lib\threading.py", line 222, in wait
_sleep(delay)
IOError: [Errno 4] Interrupted function call

I do development work on both Linux and Windows, and Linux doesn't
seem to behave this way.  I'm careful to make sure that the signal
handler only directly interacts with the main thread to be safe, but
the must be something I'm missing.

I took a simple threading example and modified to demonstrate the
problem.  It fails the same way, every time I run it on Windows, and
it works find each time on Linux.

I temporarly stuck in a try/except block to just ignore IOErrors, but
that seems like a faulty approach.  I would have to add try/except
block everywhere I call anything that could potentially call sleep(),
which seems like a poor (and painful) solution.  I also thought about
replacing threading._sleep with a try/except wrapper function, but
that seems kind of evil.

Thanks in advance for any suggestions,

Lowell Alleman


-

import threading
import signal
import time, random

class Counter:
def __init__(self):
self.lock = threading.Lock()
self.value = 0
def increment(self):
self.lock.acquire()
self.value = value = self.value + 1
self.lock.release()
return value

class Worker(threading.Thread):
def __init__(self):
self.done = threading.Event()
threading.Thread.__init__(self)
def run(self):
while not self.done.isSet():
# pretend we're doing something that takes 10-100 ms
value = counter.increment() # increment global counter
time.sleep(random.randint(10, 100) / 1000.0)
print self.getName(), "-- task", i, "finished", value
def stop(self):
self.done.set()

def handler(sig, frame):
print "Signal handler.  Sig=%r" % sig
global workers
for w in workers:
w.stop()

counter = Counter()
workers = [ Worker() for i in range(10) ]
for w in workers:
w.start()

# Install my custom signal handler which tells worker threads to stop
try:   # Win32
signal.signal(signal.SIGBREAK, handler)
except:   # Linux
signal.signal(signal.SIGTERM, handler)
signal.signal(signal.SIGINT, handler)

print "Please press Ctrl-C/Ctrl-Break or close the console window now..."
# Main thread sleeps waiting for work to be done...
time.sleep(60)

# Wait for all workers to finish
print "Stop All workers!"
for w in workers:
w.stop()

print "Joining all workers to main!"
for w in workers:
w.join()

-

Traceback (most recent call last):
  File "python_thread_signal_issue.py", line 45, in ?
time.sleep(60)
IOError: [Errno 4] Interrupted function call
--
http://mail.python.org/mailman/listinfo/python-list


Re: waiting on an event blocks all signals

2008-05-18 Thread Rhamphoryncus
On May 18, 9:05 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> alan schrieb:
>
> > This ignores CTRL-C on every platform I've tested:
>
> > python -c "import threading; threading.Event().wait()"
> > ^C^C^C^C
>
> > It looks to me like all signals are masked before entering wait(). Can
> > someone familiar with the internals explain and/or justify this
> > behavior? Thanks,
>
> They aren't masked. Read the docs:
>
> # Although Python signal handlers are called asynchronously as far as
> the Python user is concerned, they can only occur between the ``atomic''
> instructions of the Python interpreter. This means that signals arriving
> during long calculations implemented purely in C (such as regular
> expression matches on large bodies of text) may be delayed for an
> arbitrary amount of time.
>
> (http://docs.python.org/lib/module-signal.html)
>
> Which is what is happening here - wait is implemented in C. So the
> arriving signal is stored flagged in the interpreter so that the next
> bytecode would be the signal-handler set - but the interpreter still
> waits for the blocked call.

If a signal arrives while the thread is in a syscall it will usually
interrupt the syscall.  Most code in the interpreter will see the
EINTR error code and check if we have a signal to process, which leads
to raising a KeyboardInterrupt exception.  However, most thread
synchronization functions specified in POSIX are not interrupted by
signals, so the interpreter never has a chance do anything.  Why would
we care anyway, as Python doesn't let you intentionally interrupt a
non-main thread?
--
http://mail.python.org/mailman/listinfo/python-list


Re: waiting on an event blocks all signals

2008-05-18 Thread Diez B. Roggisch

alan schrieb:

This ignores CTRL-C on every platform I've tested:

python -c "import threading; threading.Event().wait()"
^C^C^C^C

It looks to me like all signals are masked before entering wait(). Can
someone familiar with the internals explain and/or justify this
behavior? Thanks,


They aren't masked. Read the docs:

# Although Python signal handlers are called asynchronously as far as 
the Python user is concerned, they can only occur between the ``atomic'' 
instructions of the Python interpreter. This means that signals arriving 
during long calculations implemented purely in C (such as regular 
expression matches on large bodies of text) may be delayed for an 
arbitrary amount of time.



(http://docs.python.org/lib/module-signal.html)

Which is what is happening here - wait is implemented in C. So the 
arriving signal is stored flagged in the interpreter so that the next 
bytecode would be the signal-handler set - but the interpreter still 
waits for the blocked call.


Diez
--
http://mail.python.org/mailman/listinfo/python-list


Re: waiting on an event blocks all signals

2008-05-17 Thread alan
On May 17, 3:06 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Sat, 17 May 2008 12:49:54 -0700, John Schroeder <[EMAIL PROTECTED]> wrote:
> >On Sat, May 17, 2008 at 12:32 PM, alan <[EMAIL PROTECTED]> wrote:
>
> >> This ignores CTRL-C on every platform I've tested:
>
> >> python -c "import threading; threading.Event().wait()"
> >> ^C^C^C^C
>
> >> It looks to me like all signals are masked before entering wait(). Can
> >> someone familiar with the internals explain and/or justify this
> >> behavior? Thanks,
>
> >^C only kills the main thread.  Use Control-Break to kill all threads.
>
> Look at that program.  It's single-threaded.  Where do you think the ^C
> is going? :)
>
> Jean-Paul

Look at this program which is also "single-threaded." Clearly,
python's doing something special. I'm hoping someone can tell me what,
and why.

/*
  pthreadsig.c

  $ gcc pthreadsig.c -lpthread
  $ ./a.out
  ^C
  $
*/

#include 

int main(int argc, char** argv) {
  int rc = 0;

  pthread_mutex_t mtx;
  pthread_cond_t cond;
  pthread_mutex_init(&mtx, 0);
  pthread_cond_init(&cond, 0);

  pthread_mutex_lock(&mtx);
  rc = pthread_cond_wait(&cond, &mtx);
  pthread_mutex_unlock(&mtx);

  return rc;
}
--
http://mail.python.org/mailman/listinfo/python-list


Re: waiting on an event blocks all signals

2008-05-17 Thread alan grow
On Sat, May 17, 2008 at 2:49 PM, John Schroeder <[EMAIL PROTECTED]> wrote:
> ^C only kills the main thread.  Use Control-Break to kill all threads.
>>
>> python -c "import threading; threading.Event().wait()"
>> ^C^C^C^C

There's a single main thread here though. Or am I missing something?
--
http://mail.python.org/mailman/listinfo/python-list


Re: waiting on an event blocks all signals

2008-05-17 Thread Jean-Paul Calderone

On Sat, 17 May 2008 12:49:54 -0700, John Schroeder <[EMAIL PROTECTED]> wrote:

On Sat, May 17, 2008 at 12:32 PM, alan <[EMAIL PROTECTED]> wrote:


This ignores CTRL-C on every platform I've tested:

python -c "import threading; threading.Event().wait()"
^C^C^C^C

It looks to me like all signals are masked before entering wait(). Can
someone familiar with the internals explain and/or justify this
behavior? Thanks,



^C only kills the main thread.  Use Control-Break to kill all threads.



Look at that program.  It's single-threaded.  Where do you think the ^C
is going? :)

Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: waiting on an event blocks all signals

2008-05-17 Thread John Schroeder
^C only kills the main thread.  Use Control-Break to kill all threads.

On Sat, May 17, 2008 at 12:32 PM, alan <[EMAIL PROTECTED]> wrote:

> This ignores CTRL-C on every platform I've tested:
>
> python -c "import threading; threading.Event().wait()"
> ^C^C^C^C
>
> It looks to me like all signals are masked before entering wait(). Can
> someone familiar with the internals explain and/or justify this
> behavior? Thanks,
>
> -Alan
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

waiting on an event blocks all signals

2008-05-17 Thread alan
This ignores CTRL-C on every platform I've tested:

python -c "import threading; threading.Event().wait()"
^C^C^C^C

It looks to me like all signals are masked before entering wait(). Can
someone familiar with the internals explain and/or justify this
behavior? Thanks,

-Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Signals/Slots support in Python

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 08:44:27 -0600, Scott SA wrote:

> Did you review this?
> 
> 
> from what I understand is originally based upon this:
> 
> 
> and subsequently integrated into this:
> 

AFAIK PyDispatcher evolved into Louie project [1]. Louie has more 
features, but dispatch module inside Django is dramatically faster and is 
going to be even faster.

[1] http://pylouie.org/

-- 
Ivan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Signals/Slots support in Python

2008-05-01 Thread Scott SA
On 5/1/08, Brian Vanderburg II ([EMAIL PROTECTED]) wrote:

>I don't know if any such support is already built in, so I ended up 
>making my own simple signals/slots like mechanism.  If anyone is 
>interested then here it is, along with a simple test.  It can connect to 
>normal functions as well as instance methods.  It also supports weak 
>connections where when an object is gone, the slot is gone as well, the 
>slot just holds a weak reference to the object.

Did you review this?
<http://pydispatcher.sourceforge.net/>

from what I understand is originally based upon this:
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/87056>

and subsequently integrated into this:
<http://djangoproject.com>

>-
># Begin Signal
>import weakref
>import random
>
>class Signal:
>class Slot:
>def __init__(self, fn):
>self.__fn = fn
>
>def __call__(self, accum, *args, **kwargs):
>result = self.__fn(*args, **kwargs)
>return accum(result)
>
>class WeakSlot:
>def __init__(self, conn, parent, fn, obj):
>self.__conn = conn
># Avoid circular references so deleting a signal will
># allow deletion of the signal since the slot doesn't ref
># back to it but only weakefs back to it
>self.__parent = weakref.ref(parent)
>
>self.__fn = fn
>self.__obj = weakref.ref(obj, self.Cleanup)
>
>def __call__(self, accum, *args, **kwargs):
>obj = self.__obj()
>if obj is None:
>return True
>
>result = self.__fn(obj, *args, **kwargs)
>return accum(result)
>
>def Cleanup(self, ref):
>parent = self.__parent()
>if parent is not None:
>parent.Disconnect(self.__conn)
>
>class Accumulator:
>def __call__(self, *args, **kwargs):
>return True
>
>def Finalize(self):
>return None
>
>def __init__(self):
>self.__slots = [ ]
>
># This connects a signal to a slot, but stores a strong reference so
># The object will not be deleted as long as the signal is connected
>def Connect(self, fn):
>conn = self.NewConn()
>self.__slots.append([conn, Signal.Slot(fn)])
>return conn
>
># This connects a signal to a slot, but store a weak reference so
># when the object is gone the slot will not be called.  Because of
># the implemenations, it is not possible to do WeakConnect(obj.Fn),
># since obj.Fn is a new object and would go to 0 refcount soon after
># the call to WeakConnect completes.  Instead we must do a call as
># WeakConnect(ObjClass.Fn, obj)
># Only the object is weak-referenced.  The function object is still
># a normal reference, this ensures that as long as the object exists
># the function will also exist.  When the object dies, the slot will
># be removed
>def WeakConnect(self, fn, obj):
>conn = self.NewConn()
>self.__slots.append([conn, Signal.WeakSlot(conn, self, fn, obj)])
>return conn
>
># Disconnect a slot
>def Disconnect(self, conn):
>result = self.Find(conn)
>if result >= 0:
>del self.__slots[result]
>
># Disconnect all slots
>def DisconnectAll(self):
>self.__slots = [ ]
>
># Create an accumulator.  Accumulator will be called as a callable
># for each return value of the executed slots.  Execution of slots
># continues as long as the reutrn value of the accumulator call is
># True.  The 'Finalize'function will be called to get the result
># A custom accumulator can be created by deriving from Signal and
># Creating a custom 'Accumulator' class, or by deriving from Singal
># and creating CreateAccumulator
>def CreateAccumulator(self):
>return self.Accumulator()
>
># Execute the slots
>def __call__(self, *args, **kwargs):
>accum = self.CreateAccumulator()
>for conn in xrange(len(self.__slots)):
>if not self.__slots[conn][1](accum, *args, **kwargs):
>break
>return accum.Finalize()
>
># Create a connection name
>def NewConn(self):
>value = 0
>while self.Find(value) >= 0:
>value = random.randint(1, 1)
>return value
>
>def Find(self, conn):
>for i in xrange(len(self.__slots)):
>if self.

Signals/Slots support in Python

2008-05-01 Thread Brian Vanderburg II
I don't know if any such support is already built in, so I ended up 
making my own simple signals/slots like mechanism.  If anyone is 
interested then here it is, along with a simple test.  It can connect to 
normal functions as well as instance methods.  It also supports weak 
connections where when an object is gone, the slot is gone as well, the 
slot just holds a weak reference to the object.


Brian Vanderburg II


# Begin Signal
import weakref
import random

class Signal:
class Slot:
def __init__(self, fn):
self.__fn = fn

def __call__(self, accum, *args, **kwargs):
result = self.__fn(*args, **kwargs)
return accum(result)

class WeakSlot:
def __init__(self, conn, parent, fn, obj):
self.__conn = conn
# Avoid circular references so deleting a signal will
# allow deletion of the signal since the slot doesn't ref
# back to it but only weakefs back to it
self.__parent = weakref.ref(parent)

self.__fn = fn
self.__obj = weakref.ref(obj, self.Cleanup)

def __call__(self, accum, *args, **kwargs):
obj = self.__obj()
if obj is None:
return True

result = self.__fn(obj, *args, **kwargs)
return accum(result)

def Cleanup(self, ref):
parent = self.__parent()
if parent is not None:
parent.Disconnect(self.__conn)

class Accumulator:
def __call__(self, *args, **kwargs):
return True

def Finalize(self):
return None

def __init__(self):
self.__slots = [ ]

# This connects a signal to a slot, but stores a strong reference so
# The object will not be deleted as long as the signal is connected
def Connect(self, fn):
conn = self.NewConn()
self.__slots.append([conn, Signal.Slot(fn)])
return conn

# This connects a signal to a slot, but store a weak reference so
# when the object is gone the slot will not be called.  Because of
# the implemenations, it is not possible to do WeakConnect(obj.Fn),
# since obj.Fn is a new object and would go to 0 refcount soon after
# the call to WeakConnect completes.  Instead we must do a call as
# WeakConnect(ObjClass.Fn, obj)
# Only the object is weak-referenced.  The function object is still
# a normal reference, this ensures that as long as the object exists
# the function will also exist.  When the object dies, the slot will
# be removed
def WeakConnect(self, fn, obj):
conn = self.NewConn()
self.__slots.append([conn, Signal.WeakSlot(conn, self, fn, obj)])
return conn

# Disconnect a slot
def Disconnect(self, conn):
result = self.Find(conn)
if result >= 0:
del self.__slots[result]

# Disconnect all slots
def DisconnectAll(self):
self.__slots = [ ]

# Create an accumulator.  Accumulator will be called as a callable
# for each return value of the executed slots.  Execution of slots
# continues as long as the reutrn value of the accumulator call is
# True.  The 'Finalize'function will be called to get the result
# A custom accumulator can be created by deriving from Signal and
# Creating a custom 'Accumulator' class, or by deriving from Singal
# and creating CreateAccumulator
def CreateAccumulator(self):
return self.Accumulator()

# Execute the slots
def __call__(self, *args, **kwargs):
accum = self.CreateAccumulator()
for conn in xrange(len(self.__slots)):
if not self.__slots[conn][1](accum, *args, **kwargs):
break
return accum.Finalize()

# Create a connection name
def NewConn(self):
value = 0
while self.Find(value) >= 0:
value = random.randint(1, 1)
return value

def Find(self, conn):
for i in xrange(len(self.__slots)):
if self.__slots[i][0] == conn:
return i

return -1

# End Signal

def fn1():
print "Hello World"

def fn2():
print "Goodbye Space"

class O:
def __init__(self, value):
self.value = value

def Action(self):
print "O %d" % self.value

a = Signal()

a.Connect(fn1)
a.Connect(fn2)

print "Part 1"
a()

a.DisconnectAll()

o1 = O(4)
o2 = O(12)

a.WeakConnect(O.Action, o1)
a.Connect(o2.Action)

print "Part 2"
a()

print "Part 3"
o1 = None
a()

print "Part 4"
o2 = None
a()

a.DisconnectAll()

def f1():
print "Hello Neighbor"

def f2():
print "Back to Work"

c1 = a.Connect(f1)
c2 

PyGTK GUI update without signals from GUI

2008-04-12 Thread Andrew Lapidas
Hi All:

I am currently having a problem updating a GUI.

I am using PyGTK and Glade to design an interface for a project.  This
interface contains no buttons, just images, labels, and a progress
bar.  The code for the project is small, and it basically does some
things independent of the GUI in an infinite loop.  I need the project
code to update the GUI intermittently.  I have found, though, that
generally it seems that the gtk.main loop is looking for signals from
the GUI and I cannot figure out how to give it signals from another
application.  I have thought spawning a new thread from the __init__
in the GUI and somehow having it send signals to gtk.main, but I do
not know if this will work.

Any opinions or ideas on this subject would be greatly appreciated.

Thank you in advance,
Andy
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] Scope_Plot, another plot library for real time signals.

2007-11-04 Thread Stef Mientki
hello,

I justed finished, another plot library, called Scope_Plot, based on 
wxPython.

Scope_Plot is special meant for displaying real time signals,
and therefor has some new functionalities:
- signal selection
- each signal has it's own scale,
- moving erase block
- measurement cursor
ans should be a lot faster than MatPlot, Plot and FloatCanvas,
at least for real time signals (because it only draws the changes).

An animated demo can be seen here (2 MB, 2:10):
  http://stef.mientki.googlepages.com/jalspy_scope.html

A description of the library, as used in an application, can be found here:
  http://oase.uci.kun.nl/~mientki/data_www/pic/jalspy/jalspy_scope.html

And finally the file (and a few necessary libs) can be found here:
  http://oase.uci.kun.nl/~mientki/download/Scope_Plot.zip
The library has a main section which contains a simple demo,
the animated demo and the application description shows a more complex 
signal organization.

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread fumanchu
On Jun 11, 3:34 am, geoffbache <[EMAIL PROTECTED]> wrote:
> I have a Python program (on UNIX) whose main job is to listen on a
> socket, for which I use the SocketServer module. However, I would also
> like it to be sensitive to signals received, which it isn't if it's
> listening on the socket. ("signals can only be received between atomic
> actions of the python interpreter", presumably - and control will not
> return to Python unless something appears on the socket). Does anyone
> have a tip of a good way to do this?
>
> I can of course put the SocketServer in a thread and call
> signal.pause() in the main thread, but this falls down when the
> SocketServer terminates normally, as the signal.pause() cannot be
> interrupted except via signals. So I tried sending a "dummy" signal
> (SIGCHLD) from the thread when the SocketServer terminates, which
> seems to work on Linux but not Solaris. And which in any case feels a
> bit hackish - surely there has to be a better way?

Use a timeout on your socket and put socket.accept() in a loop:

mainsocket.settimeout(1)

while True:
try:
childsocket, addr = mainsocket.accept()
handle(childsocket, addr)
except socket.timeout:
pass


Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread geoffbache
On Jun 11, 2:08 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Mon, 11 Jun 2007 04:56:43 -0700, geoffbache <[EMAIL PROTECTED]> wrote:
>
> >> Twisted *should* be able to do this, as it uses non-blocking IO.
>
> >>http://twistedmatrix.com/trac/
>
> >Thanks for the tip. I'll take a look if nobody has any better
> >suggestions.
>
> Twisted is a pretty good suggestion in general. ;)
> >It still seems to me that what I'm trying to do is essentially quite
> >simple, and shouldn't require
> >as large a tool as Twisted to fix it. Isn't Twisted basically for web
> >applications?
>
> Twisted supports HTTP, but it does plenty of other things too.  Generally
> speaking, it's useful for any network application, plus some other stuff.
>

My application is only incidentally a network application. It doesn't
have clients
and servers as such, it just distributes its work via a grid engine
and then lets
these workers communicate back their results via sockets.

> You're half right about this being simple though, and not needing Twisted
> to solve the problem.  The only thing you need to do to solve the problem
> is avoid using either signals or threads.  Interaction between the two is
> very complicated and, as you've noticed, varies across platforms.  Twisted
> is solving the problem for you here by letting you do I/O without using
> threads, making signals *almost* simple.
>

Yes, I would avoid signals or threads if I could, but it's tough. The
program
is supposed to "appear" to just be a batch process, so handling e.g.
ctrl-C is essential.
The standard SocketServer doesn't allow for this, so I need some other
thread of control
that will, or some means of "asynchronising" SocketServer internally.

Or there's always the really hacky low tech solution which has a
certain appeal : have
the main thread check all the others for being alive and sleep in
between...

Geoff

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread geoffbache

>
> You could probably use the Asyncore stuff to do it as well (with a lot
> less stuff).

This looked interesting. But it seems the asyncore stuff operates at
the socket level,
whereas I've currently just got a standard synchronous SocketServer
and the socket
operations themselves are kind of hidden beneath this layer. Can you
point me at anything
that might tell me how to combine Asyncore with SocketServer,
preferably without having to
mess with the internals of SocketServer too much :)

Geoff


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread Chaz Ginger
geoffbache wrote:
>> Twisted *should* be able to do this, as it uses non-blocking IO.
>>
>> http://twistedmatrix.com/trac/
> 
> Thanks for the tip. I'll take a look if nobody has any better
> suggestions.
> 
> It still seems to me that what I'm trying to do is essentially quite
> simple, and shouldn't require
> as large a tool as Twisted to fix it. Isn't Twisted basically for web
> applications?
> 
> Geoff
> 
You could probably use the Asyncore stuff to do it as well (with a lot
less stuff).

C.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread Jean-Paul Calderone
On Mon, 11 Jun 2007 04:56:43 -0700, geoffbache <[EMAIL PROTECTED]> wrote:
>
>> Twisted *should* be able to do this, as it uses non-blocking IO.
>>
>> http://twistedmatrix.com/trac/
>
>Thanks for the tip. I'll take a look if nobody has any better
>suggestions.

Twisted is a pretty good suggestion in general. ;)

>
>It still seems to me that what I'm trying to do is essentially quite
>simple, and shouldn't require
>as large a tool as Twisted to fix it. Isn't Twisted basically for web
>applications?

Twisted supports HTTP, but it does plenty of other things too.  Generally
speaking, it's useful for any network application, plus some other stuff.

You're half right about this being simple though, and not needing Twisted
to solve the problem.  The only thing you need to do to solve the problem
is avoid using either signals or threads.  Interaction between the two is
very complicated and, as you've noticed, varies across platforms.  Twisted
is solving the problem for you here by letting you do I/O without using
threads, making signals *almost* simple.

Jean-Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread geoffbache

> Twisted *should* be able to do this, as it uses non-blocking IO.
>
> http://twistedmatrix.com/trac/

Thanks for the tip. I'll take a look if nobody has any better
suggestions.

It still seems to me that what I'm trying to do is essentially quite
simple, and shouldn't require
as large a tool as Twisted to fix it. Isn't Twisted basically for web
applications?

Geoff

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, signals and sockets (on UNIX)

2007-06-11 Thread Stefan Behnel
geoffbache wrote:
> I have a Python program (on UNIX) whose main job is to listen on a
> socket, for which I use the SocketServer module. However, I would also
> like it to be sensitive to signals received, which it isn't if it's
> listening on the socket. ("signals can only be received between atomic
> actions of the python interpreter", presumably - and control will not
> return to Python unless something appears on the socket). Does anyone
> have a tip of a good way to do this?

Twisted *should* be able to do this, as it uses non-blocking IO.

http://twistedmatrix.com/trac/

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Threads, signals and sockets (on UNIX)

2007-06-11 Thread geoffbache
Hi all,

I have a Python program (on UNIX) whose main job is to listen on a
socket, for which I use the SocketServer module. However, I would also
like it to be sensitive to signals received, which it isn't if it's
listening on the socket. ("signals can only be received between atomic
actions of the python interpreter", presumably - and control will not
return to Python unless something appears on the socket). Does anyone
have a tip of a good way to do this?

I can of course put the SocketServer in a thread and call
signal.pause() in the main thread, but this falls down when the
SocketServer terminates normally, as the signal.pause() cannot be
interrupted except via signals. So I tried sending a "dummy" signal
(SIGCHLD) from the thread when the SocketServer terminates, which
seems to work on Linux but not Solaris. And which in any case feels a
bit hackish - surely there has to be a better way?

Regards,
Geoff Bache

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Signals

2007-04-18 Thread Robert Rawlins - Think Blue
Thanks Carsten,

Sorry for not mentioning the dbus before, I thought that the signals were a 
general python thing, I didn’t realize it was a specific dbus thing.

I've now modified the code so it looks like this.

#!/usr/bin/python

import dbus
from gobject import MainLoop, idle_add
from dbus.mainloop.glib import DBusGMainLoop

def main_function():
bus = dbus.SystemBus()
manager = dbus.Interface(bus.get_object('org.bluez', 
'/org/bluez'),'org.bluez.Manager')
adapter = dbus.Interface(bus.get_object('org.bluez', 
manager.DefaultAdapter()),'org.bluez.Adapter')

def remote_device_found(addr, class_, rssi):
print 'Found:', addr

adapter.connect_to_signal('RemoteDeviceFound', remote_device_found)

adapter.DiscoverDevices()

if __name__ == '__main__':
idle_add(main_function)
dbus_mainloop_wrapper = DBusGMainLoop(set_as_default=True)
mainloop = MainLoop()
mainloop.run()

Which should implement the main loop and keep the application alive, however 
when running the program I get the following error thrown at me.

File "./scan4.py", line 5, in ?
from dbus.mainloop.glib import DBusGMainLoop
ImportError: No module named mainloop.glib

Any ideas what might be causing this? My guess is that I don’t have one of the 
dependency installed properly, but I have no idea which ones I need.

Thanks for any more help you can offer, its greatly appreciated.

Rob 
-Original Message-
From: Carsten Haese [mailto:[EMAIL PROTECTED] 
Sent: 18 April 2007 13:43
To: Robert Rawlins - Think Blue
Cc: python-list@python.org
Subject: Re: Signals

On Wed, 2007-04-18 at 08:39 +0100, Robert Rawlins - Think Blue wrote:
> Hello Chaps,
> 
>  
> 
> I posted about this the other day but I’m still struggling to get any
> form of result from it. Basically I have the following piece of code,
> and according to its API is produces singals when particular events
> occur, but i have no idea how to list for events, I’ve tried all sorts
> of combinations using the signal module but haven’t been able to get
> it working.
> [...]
> import dbus, signal
> [...]
>
> Now here is a copy of the API documentation that lists the signals
> thrown by the API, this is the one I’m trying to listen for.
> 
>  
> 
> void RemoteDeviceFound(string address, uint32 class, int16
> rssi)
> 
>  
> 
>This signal will be send every time an inquiry result
> 
>has been found by the service daemon. In general they
> 
>only appear during a device discovery.
> 
>  
> 
> Basically I’m just looking to run a function that will print those
> details to screen. Can anyone help with working out how to listen for
> this signal?

The signal module is for handling process signals the operating system
sends to your python process. The API you're using (dbus, a crucial
detail you neglected to mention before) doesn't send this kind of
signal.

Googling for 'python dbus documentation' brings up
http://dbus.freedesktop.org/doc/dbus-python/api/ , which seems to
explain everything you need. You need to get an instance of
dbus.Interface, which you seem to have done, and call its
connect_to_signal() method, which you don't seem to have done.

>  I’d also like to know how i can keep the application running until I
> decided to stop it manually, as the DiscoverDevices() can take a while
> to complete and send out several RemoteDeviceFound() signals in that
> period.

The very first section of the above mentioned documentation talks about
needing a main loop for receiving signals, and it provides example
boilerplate code for how to set up a main loop.

Hope this helps,

Carsten.



-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Signals

2007-04-18 Thread Carsten Haese
On Wed, 2007-04-18 at 08:39 +0100, Robert Rawlins - Think Blue wrote:
> Hello Chaps,
> 
>  
> 
> I posted about this the other day but I’m still struggling to get any
> form of result from it. Basically I have the following piece of code,
> and according to its API is produces singals when particular events
> occur, but i have no idea how to list for events, I’ve tried all sorts
> of combinations using the signal module but haven’t been able to get
> it working.
> [...]
> import dbus, signal
> [...]
>
> Now here is a copy of the API documentation that lists the signals
> thrown by the API, this is the one I’m trying to listen for.
> 
>  
> 
> void RemoteDeviceFound(string address, uint32 class, int16
> rssi)
> 
>  
> 
>This signal will be send every time an inquiry result
> 
>has been found by the service daemon. In general they
> 
>only appear during a device discovery.
> 
>  
> 
> Basically I’m just looking to run a function that will print those
> details to screen. Can anyone help with working out how to listen for
> this signal?

The signal module is for handling process signals the operating system
sends to your python process. The API you're using (dbus, a crucial
detail you neglected to mention before) doesn't send this kind of
signal.

Googling for 'python dbus documentation' brings up
http://dbus.freedesktop.org/doc/dbus-python/api/ , which seems to
explain everything you need. You need to get an instance of
dbus.Interface, which you seem to have done, and call its
connect_to_signal() method, which you don't seem to have done.

>  I’d also like to know how i can keep the application running until I
> decided to stop it manually, as the DiscoverDevices() can take a while
> to complete and send out several RemoteDeviceFound() signals in that
> period.

The very first section of the above mentioned documentation talks about
needing a main loop for receiving signals, and it provides example
boilerplate code for how to set up a main loop.

Hope this helps,

Carsten.


-- 
http://mail.python.org/mailman/listinfo/python-list

Signals

2007-04-18 Thread Robert Rawlins - Think Blue
Hello Chaps,

 

I posted about this the other day but I'm still struggling to get any form
of result from it. Basically I have the following piece of code, and
according to its API is produces singals when particular events occur, but i
have no idea how to list for events, I've tried all sorts of combinations
using the signal module but haven't been able to get it working.

 

#!/usr/bin/python

 

import dbus, signal

 

bus = dbus.SystemBus()

obj = bus.get_object('org.bluez', '/org/bluez')

obj = bus.get_object('org.bluez', '/org/bluez/hci0')

adapter = dbus.Interface(obj, 'org.bluez.Adapter')

 

adapter.DiscoverDevices()

 

Now here is a copy of the API documentation that lists the signals thrown by
the API, this is the one I'm trying to listen for.

 

void RemoteDeviceFound(string address, uint32 class, int16 rssi)

 

   This signal will be send every time an inquiry result

   has been found by the service daemon. In general they

   only appear during a device discovery.

 

Basically I'm just looking to run a function that will print those details
to screen. Can anyone help with working out how to listen for this signal?
I'd also like to know how i can keep the application running until I decided
to stop it manually, as the DiscoverDevices() can take a while to complete
and send out several RemoteDeviceFound() signals in that period.

 

Thanks guys

 

Rob

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Queue and signals

2007-01-16 Thread hg
[EMAIL PROTECTED] wrote:

> 
> >> Is it legal to use Queue.put in a signal handle and Queue.get in
> >> the main process (no thread)
> 
> hg> PS: and if not is there a way to share data between a "main" and
> its hg> signal in a safe way (write in signal and read in main)
> 
> The Queue module was designed to work in multithreaded contexts.  I doubt
> it
> will work as expected in a nonthreaded application.  Given that your
> application isn't multithreaded I suspect you can just modify an object
> that
> both your signal handler and the rest of the application reference.  In
> particular, there's no reason your signal handler can't be a method of an
> instance:
> 
> import signal
> import time
> 
> class MyClass:
> def __init__(self):
> self.alarm_rang = False
> signal.signal(signal.SIGALRM, self.ring_alarm)
> signal.alarm(2)
> 
> def ring_alarm(self, sig, frame):
> self.alarm_rang = True
> 
> obj = MyClass()
> print obj.alarm_rang
> time.sleep(4.0)
> print obj.alarm_rang
> 
> Skip

Hi,

Well, so far it seems to work ...

The signal handler gets "called" by another application which in turn will
stuff info in my sys.stdin, I need then to "raw_input" the info and put it
in some type of data structure in a safe way so my main loop can then
reader/pop it.

ref: (ps: I'm trying to setup a Python high level interface for my kids to
learn the language / be interested) http://realtimebattle.sourceforge.net/

Regards,

hg


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue and signals

2007-01-16 Thread skip

>> Is it legal to use Queue.put in a signal handle and Queue.get in the
>> main process (no thread)

hg> PS: and if not is there a way to share data between a "main" and its
hg> signal in a safe way (write in signal and read in main)

The Queue module was designed to work in multithreaded contexts.  I doubt it
will work as expected in a nonthreaded application.  Given that your
application isn't multithreaded I suspect you can just modify an object that
both your signal handler and the rest of the application reference.  In
particular, there's no reason your signal handler can't be a method of an
instance:

import signal
import time

class MyClass:
def __init__(self):
self.alarm_rang = False
signal.signal(signal.SIGALRM, self.ring_alarm)
signal.alarm(2)

def ring_alarm(self, sig, frame):
self.alarm_rang = True

obj = MyClass()
print obj.alarm_rang
time.sleep(4.0)
print obj.alarm_rang

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue and signals

2007-01-16 Thread hg
hg wrote:

> Hi,
> 
> Is it legal to use Queue.put in a signal handle and Queue.get in the main
> process (no thread)
> 
> Thanks,
> 
> hg


PS: and if not is there a way to share data between a "main" and its signal
in a safe way (write in signal and read in main)

Thanks,

hg

-- 
http://mail.python.org/mailman/listinfo/python-list


Queue and signals

2007-01-16 Thread hg
Hi,

Is it legal to use Queue.put in a signal handle and Queue.get in the main
process (no thread)

Thanks,

hg

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: catching signals in an object

2007-01-15 Thread robert
hg wrote:
> Hi,
> 
> I need to catch a signal "SIGUSR1" in an object ... and I need the signal
> def that traps is to access the object context ... is that possible  ?
> (*nix and windows)
> 
> ex:
> 
> class test:
> def __init__(self):
> self.Set_Signal()
> 
> def Set_Signal(self):
> import signal
> signal.signal(..., Func)
> def Func(.):
> #I need to get access to self
> 
> 
> or can signal.signal take a method as param ?
> 

Just do it! Python is a functional language.
You have access to self (search for the term "closure") and 
self.method is bound - thus a 'function'

objects are nothing special in Python.


Robert
-- 
http://mail.python.org/mailman/listinfo/python-list


catching signals in an object

2007-01-15 Thread hg
Hi,

I need to catch a signal "SIGUSR1" in an object ... and I need the signal
def that traps is to access the object context ... is that possible  ?
(*nix and windows)

ex:

class test:
def __init__(self):
self.Set_Signal()

def Set_Signal(self):
import signal
signal.signal(..., Func)
def Func(.):
#I need to get access to self


or can signal.signal take a method as param ?

Thanks

hg

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Joining threads but allowing signals to main thread?

2007-01-11 Thread Lloyd Zusman
Gabriel Genellina <[EMAIL PROTECTED]> writes:

> At Thursday 11/1/2007 03:43, Lloyd Zusman wrote:
>
>>   while threading.activeCount() > 1:
>>   time.sleep(0.001)
>>
>>   sys.exit(0)
>>
>>Is there any way to allow my program to respond to signals without
>>having to busy-wait in the main thread?
>
> Don't worry too much, this is *not* a busy wait, because you use
> sleep. You can use a longer sleep, it will be terminated by any
> signal. But not too long, or the check for activeCount() will be delayed
> in excess. (I use sleep(1) usually but your needs may be different)

Well, if this is the best that we can currently do in python, then so be
it.

My sincere thanks.


-- 
 Lloyd Zusman
 [EMAIL PROTECTED]
 God bless you.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Joining threads but allowing signals to main thread?

2007-01-10 Thread Gabriel Genellina

At Thursday 11/1/2007 03:43, Lloyd Zusman wrote:


  while threading.activeCount() > 1:
  time.sleep(0.001)

  sys.exit(0)

Is there any way to allow my program to respond to signals without
having to busy-wait in the main thread?


Don't worry too much, this is *not* a busy wait, because you use 
sleep. You can use a longer sleep, it will be terminated by any 
signal. But not too long, or the check for activeCount() will be 
delayed in excess. (I use sleep(1) usually but your needs may be different)



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

-- 
http://mail.python.org/mailman/listinfo/python-list

Joining threads but allowing signals to main thread?

2007-01-10 Thread Lloyd Zusman
I have a python-2.5 program running under linux in which I spawn a
number of threads.  The main thread does nothing while these subsidiary
threads are running, and after they all complete, the main thread will
then exit.

I know that I can manage this through the use of Thread.join(), but
when I do it as follows, the main thread doesn't respond to signals:

  import sys, time, signal, threading

  signaled = False

  class Signaled(Exception):
  pass

  def sighandler(signum, frame):
  global signaled
  print 'aborted!'
  signaled = True

  def sigtest():
  global signaled
  if signaled:
  raise Signaled

  def myfunc(arg):
  while True:
  try:
  sigtest()
  # do something
  except Signaled:
  return

  threads = []
  for a in sys.argv[1:]:
  t = threading.Thread(myfunc, args=(a,))
  threads.append(t)

  # do some initialization

  for s in (signal.SIGHUP,  \
signal.SIGINT,  \
signal.SIGQUIT, \
signal.SIGTERM):
  signal.signal(s, sighandler)

  for t in threads:
  t.start()

  for t in threads:
  t.join()

  sys.exit(0)

However, if I get rid of the t.join() loop and replace the last three
executable lines of the program with these, the main thread responds to
signals just fine:

  ...

  while threading.activeCount() > 1:
  time.sleep(0.001)

  sys.exit(0)

Is there any way to allow my program to respond to signals without
having to busy-wait in the main thread?

Thanks in advance.


-- 
 Lloyd Zusman
 [EMAIL PROTECTED]
 God bless you.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads and signals

2006-11-16 Thread Chad J. Schroeder
By writing a little C module I fixed the problem.  By simply calling
the function in the child thrd's run method, things work as expected.

This is all the function (blockall) does:

sigset_t   omask, nmask;
sigfillset(&nmask);
sigprocmask(SIG_SETMASK, &nmask, NULL);

bash-2.05b# python2.5 ./thrd_test.py
Starting up
MainThread.run():  71799
ChildThread.run():  71799
ChildThread before sleep(10)
MainThread before sleep(15)
^CReceived signal  2
flag:  True
flag:  False
MainThread after sleep(15)
Shutting down
bash-2.05b#

Chad

> I've run into an "opportunity" in a Python application using threads
> and signals.  Basically, there is a main process that spawns off a child 
> thread that loops forever.  In between iterations, the child
> thread sleeps for X seconds. All the while, the main thread loops
> forever doing its thing and also sleeps in between iterations (see the code 
> at 
> the end this message). Normally the application would
> be daemonized before the main process starts up. Hence, during a
> system shutdown or stoppage of the daemon, it's desired that the
> daemon catch a few signals (TERM/INT) and perform a few cleanup
> routines. According to the Python docs, only the main thread will receive 
> signals. The problem I have, on FreeBSD systems, is that the sleep
> function in the child gets interrupted and the signal never gets handled
> until the main thread's sleep concludes.  It works as expected on a Linux
> box (main thrd's sleep is interrupted).  Sample output from multiple systems 
> is directly below.
>
> Just looking for insight from others in the know.
>
> Thanks,
> Chad
>
>
> Linux 2.6.17
> 
> test_bed$ python2.5 ./thrd_test.py
> Starting up
> MainThread.run(): 14332
> MainThread before sleep(15)
> ChildThread.run(): 14332
> ChildThread before sleep(10)
> Received signal 2<-- Interrupted here (Ctrl-C), correctly
> flag: Trueinterrupts sleep in main thread
> flag: False
> MainThread after sleep(15)
> Shutting down
>
> test_bed$ python2.4 ./thrd_test.py
> Starting up
> MainThread.run(): 14338
> MainThread before sleep(15)
> ChildThread.run(): 14338
> ChildThread before sleep(10)
> Received signal 2 <-- Interrupted here (Ctrl-C), correctly
> flag: Trueinterrupts sleep in main thread
> flag: False
> MainThread after sleep(15)
> Shutting down
> test_bed$
>
> FreeBSD 4.11, 6.1, and 6.2
> 
> bash-2.05b# python2.5 ./thrd_test.py
> Starting up
> MainThread.run(): 65930
> ChildThread.run(): 65930
> ChildThread before sleep(10)
> MainThread before sleep(15)
> ^CChildThread after sleep(10)  <-- Interrupted here (Ctrl-C), but
> ChildThread before sleep(10) interrupts the child thrd's sleep
> ChildThread after sleep(10)
> ChildThread before sleep(10)
> Received signal 2<-- Main sleep concludes and 
> then 
> flag: True   the signal gets handled
> flag: False
> MainThread after sleep(15)
> Shutting down
> bash-2.05b#
>
>
> #--- CODE BEGIN ---#
>
> #!/usr/bin/env python
>
> import os
> import sys
> import time
> import signal
> import threading
>
> def sigHandle(signo, stkframe):
>print "Received signal ", signo
>print "flag: ", mthrd.flag.isSet()
>mthrd.flag.clear()
>print "flag: ", mthrd.flag.isSet()
>
> class ChildThread(threading.Thread):
>
>def __init__(self):
>threading.Thread.__init__(self)
>
>def run(self):
>print "ChildThread.run(): ", os.getpid()
  mymod.blockall()
>while (True):
>print "ChildThread before sleep(10)"
>time.sleep(10)
>print "ChildThread after sleep(10)"
>
> class MainThread(object):
>
>def __init__(self):
>self.flag = threading.Event()
>self.cthrd = ChildThread()
>self.cthrd.setDaemon(True)
>
>def run(self):
>print "MainThread.run(): ", os.getpid()
>self.flag.wait()
>self.cthrd.start()
>while (self.flag.isSet()):
>print "MainThread before sleep(15)"
>time.sleep(15)
>print "MainThread after sleep(15)"
>return# or cleanup routine
>
> if __name__ == "__main__":
>
># Normally, the process is daemonized first. That's been
># left out for testing purposes.
>
>signal.signal(signal.SIGINT, sigHandle)
>signal.signal(signal.SIGQUIT, sigHandle)
>signal.signal(signal.SIGTERM, sigHandle)
>
>mthrd = MainThread()
>print "Starting up"
>mthrd.flag.set()
>mthrd.run()
>print "Shutting down"
>
>sys.exit(0)
>
> #--- CODE END ---# 

-- 
http://mail.python.org/mailman/listinfo/python-list


Threads and signals

2006-11-15 Thread Chad J. Schroeder
I've run into an "opportunity" in a Python application using threads and 
signals.
Basically, there is a main process that spawns off a child thread that loops 
forever.
In between iterations, the child thread sleeps for X seconds. All the while, 
the 
main
thread loops forever doing its thing and also sleeps in between iterations (see 
the code
at the end this message). Normally the application would be daemonized before 
the main
process starts up. Hence, during a system shutdown or stoppage of the daemon, 
it's
desired that the daemon catch a few signals (TERM/INT) and perform a few cleanup
routines. According to the Python docs, only the main thread will receive 
signals. The
problem I have, on FreeBSD systems, is that the sleep function in the child 
gets 
interrupted
and the signal never gets handled until the main thread's sleep concludes. It 
works as
expected on a Linux box (main thrd's sleep is interrupted). Sample output from 
multiple
systems is directly below.

Just looking for insight from others in the know.

Thanks,
Chad


Linux 2.6.17

test_bed$ python2.5 ./thrd_test.py
Starting up
MainThread.run(): 14332
MainThread before sleep(15)
ChildThread.run(): 14332
ChildThread before sleep(10)
Received signal 2<-- Interrupted here (Ctrl-C), correctly
flag: Trueinterrupts sleep in main thread
flag: False
MainThread after sleep(15)
Shutting down

test_bed$ python2.4 ./thrd_test.py
Starting up
MainThread.run(): 14338
MainThread before sleep(15)
ChildThread.run(): 14338
ChildThread before sleep(10)
Received signal 2 <-- Interrupted here (Ctrl-C), correctly
flag: Trueinterrupts sleep in main thread
flag: False
MainThread after sleep(15)
Shutting down
test_bed$

FreeBSD 4.11, 6.1, and 6.2

bash-2.05b# python2.5 ./thrd_test.py
Starting up
MainThread.run(): 65930
ChildThread.run(): 65930
ChildThread before sleep(10)
MainThread before sleep(15)
^CChildThread after sleep(10)  <-- Interrupted here (Ctrl-C), but
ChildThread before sleep(10) interrupts the child thrd's sleep
ChildThread after sleep(10)
ChildThread before sleep(10)
Received signal 2<-- Main sleep concludes and then 
the
flag: True   signal gets handled
flag: False
MainThread after sleep(15)
Shutting down
bash-2.05b#


#--- CODE BEGIN ---#

#!/usr/bin/env python

import os
import sys
import time
import signal
import threading

def sigHandle(signo, stkframe):
print "Received signal ", signo
print "flag: ", mthrd.flag.isSet()
mthrd.flag.clear()
print "flag: ", mthrd.flag.isSet()

class ChildThread(threading.Thread):

def __init__(self):
threading.Thread.__init__(self)

def run(self):
print "ChildThread.run(): ", os.getpid()
while (True):
print "ChildThread before sleep(10)"
time.sleep(10)
print "ChildThread after sleep(10)"

class MainThread(object):

def __init__(self):
self.flag = threading.Event()
self.cthrd = ChildThread()
self.cthrd.setDaemon(True)

def run(self):
print "MainThread.run(): ", os.getpid()
self.flag.wait()
self.cthrd.start()
while (self.flag.isSet()):
print "MainThread before sleep(15)"
time.sleep(15)
print "MainThread after sleep(15)"
return# or cleanup routine

if __name__ == "__main__":

# Normally, the process is daemonized first. That's been
# left out for testing purposes.

signal.signal(signal.SIGINT, sigHandle)
signal.signal(signal.SIGQUIT, sigHandle)
signal.signal(signal.SIGTERM, sigHandle)

mthrd = MainThread()
print "Starting up"
mthrd.flag.set()
mthrd.run()
print "Shutting down"

sys.exit(0)

#--- CODE END ---# 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Signals and threads again

2006-10-13 Thread Mitko Haralanov
On Fri, 13 Oct 2006 11:37:46 -0700
Mitko Haralanov <[EMAIL PROTECTED]> wrote:

> The problem that I am experiencing is that when SIGINT is sent to the
> program, it gets delivered to the child processes (the fork'ed ones)
> but the main thread's signal handler is never invoked.
> 
> I know that Python masks signals in threads but they should be fine in
> the main thread and that is where they should get delivered.

OK. I did an experiment where instead of creating a spinning thread, I
just call that function. Now, the signal gets delivered to the main
program thread but it sill get delivered to the child processes, as
well.

Why are those signals going there?? It's driving me crazy!

-- 
Mitko Haralanov  [EMAIL PROTECTED]
Senior Software Engineer 650.934.8064
System Interconnect Group   http://www.qlogic.com

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >