Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Steven D'Aprano
On Sun, May 14, 2017 at 10:57:57PM -0500, Jim wrote:
> I am running this on Mint 18.
> This is the third script I have written to open and position windows in 
> workspaces. The first two work, but trying to open ebook-viewe r 
> (calibre) with a specific book produces the following error.
> If I run the same command in the terminal it works without an error.

I think your problem is that you're telling subprocess to run a command 
called:

ebook-viewer 
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub

with no arguments. What you want is a command called:

ebook-viewer

and a single argument:
 
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub

I think (but haven't tried it) that the simplest way to fix that is to 
change the entry in self.programs from:

> self.programs = ['jedit', 'google-chrome', 'doublecmd',
> 'ebook-viewer 
> /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']

to:

path_to_file = 
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'
self.programs = ['jedit', 
 'google-chrome', 
 'doublecmd',
 ['ebook-viewer', path_to_file],
 ]
  

and see if that fixes it. (It may not be enough, or the right approach, 
but at least you'll get a different error if it is wrong :-)

The difference is that the shell automatically splits things on spaces, 
so it sees the space between ebook-viewer and the long path, and treats 
the first word as the executable and the second as an argument. But 
Python treats the whole string, spaces and quotes included, as the 
executable.


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Peter Otten
Jim wrote:

> I am running this on Mint 18.
> This is the third script I have written to open and position windows in
> workspaces. The first two work, but trying to open ebook-viewe r
> (calibre) with a specific book produces the following error.
> If I run the same command in the terminal it works without an error.
> 
> 
> Exception in thread Thread-4:
> Traceback (most recent call last):
>File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
>  self.run()
>File "/usr/lib/python3.5/threading.py", line 862, in run
>  self._target(*self._args, **self._kwargs)
>File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in
> open_it
>  subprocess.call([self.program])
>File "/usr/lib/python3.5/subprocess.py", line 557, in call
>  with Popen(*popenargs, **kwargs) as p:
>File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
>  restore_signals, start_new_session)
>File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
>  raise child_exception_type(errno_num, err_msg)
> FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer
> 
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'
> 
> Code:
> 
> # place_windows_OO_WS3.py
> 
> import subprocess
> from subprocess import Popen,PIPE
> import threading
> import time
> 
> class Place():
> 
>  def __init__(self):
>  self.programs = ['jedit', 'google-chrome', 'doublecmd',
>  'ebook-viewer
> 
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']
>  self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
>  'google-chrome':'google-chrome',
>  'doublecmd':'doublecmd',
>  'calibre-ebook-viewer': 'libprs500'}
>  self.open_and_move()
> 
>  def open_it(self):
>  subprocess.call([self.program])
> 
>  def open_and_move(self):
>  for self.program in self.programs:
>  opener = threading.Thread(target=self.open_it)
>  opener.start()
>  time.sleep(2)
>  p = Popen(['xdotool', 'search', '--classname',
> self.classname[self.program]], stdout=subprocess.PIPE)
> 
>  if self.classname[self.program] == 'sun-awt-X11-XFramePeer':
>  wid = str(p.stdout.read())
>  wid = wid[len(wid) - 11 : len(wid) - 3]
>  x = '0'
>  y = '0'
>  print('***jedit***')
>  elif self.classname[self.program] == 'google-chrome':
>  wid = str(p.stdout.read())
>  wid = wid[len(wid) - 11 : len(wid) - 3]
>  x = '1924'
>  y = '0'
>  print('***google***')
>  elif self.classname[self.program] == 'doublecmd':
>  wid = str(p.stdout.read())
>  wid = wid[len(wid) - 11 : len(wid) - 3]
>  x = '1924'
>  y = '537'
>  print('***double***')
>  else:
>  wid = str(p.stdout.read())
>  wid = wid[len(wid) - 11 : len(wid) - 3]
>  x = '2540' #'1924'
>  y = '537'
>  print('***calibre***')
>  subprocess.call(['xdotool', 'windowmove', str(wid), x, y])
> 
> I did some googling and it seems that subprocess does not have a length
> limit in linux. Could someone tell me how to correct the above error.

Not directly related to your question, but I think you should have one 
instance of your Place class per program. That way you keep related 
information together and avoid the need to look it up in a dict or find it 
with a long chain of if ... elif ... tests. For example:

# untested
import subprocess
import threading
import time

DELAY = 3.0  # seconds


class Place:
def __init__(self, cmd, classname=None, name=None, x=0, y=0):
if classname is None:
classname = cmd[0]
if name is None:
name = cmd[0]

self.cmd = cmd
self.classname = classname
self.name = name
self.x = x
self.y = y

def open_it(self):
subprocess.call(self.cmd)

def open_and_move(self):
opener = threading.Thread(target=self.open_it)
opener.start()
time.sleep(DELAY)
output = subprocess.Popen(
['xdotool', 'search', '--classname', self.classname],
stdout=subprocess.PIPE
).communicate()[0]
wid = output.split()[-1].decode()
subprocess.call(
[
'xdotool', 'windowmove',
wid, str(self.x), str(self.y)
]
)
print("***{}***".format(self.name))

EBOOK = (
"/home/jfb/Documents/eBooks/Javascript/"
"GOOGLE_SHEETS/googlespreadsheetprogramming.epub"
)

programs = [
Place(["jedit"], classname="sun-awt-X11-XFramePe

[Tutor] Tkinter + frame + grid question

2017-05-15 Thread Phil
Thank you for reading this.

I'd like to place a red frame in the centre of the main window.

I've discovered two ways to achieve this using place() and pack(padx, pady). 
Grid() does not give the desired result.

Next I'd like to place some widgets on the frame. Again place() does what I 
want and pack() almost does except the red frame is the size of the padding. It 
now seems to me that this is the way it's supposed to work. I'd like to use 
grid(), but so far, all that I can achieve is to place widgets on the main 
window and not the frame. The frame does not display if I use grid().

I've spent hours on this and an Internet search has not helped at all. However, 
I did learn that grid() and pack() are not compatible, could this be the 
problem? Perhaps I have to let go of the familiar grid() method and use pack() 
instead? Place() does exactly what I want but it's a bit cumbersome to use. The 
more I think about it, the more I think pack() is the go.

Still, I'd like to know, what's the best method?

The following is a summary of what I've tried:

from tkinter import *

class App:

def __init__(self, master):
master.geometry('400x400+50+50')
frame = Frame(master, width = 300, height = 300, bg = 'red')

frame.pack(pady = 50)
#frame.place(x = 50, y = 50)


Entry(frame).place(x = 100, y = 100, anchor = CENTER)
#Entry(frame).pack(padx = 20, pady = 20)
#Entry(frame).grid(row = 10, column = 1)

#Entry2 = Entry
#Entry2(frame).grid(row = 20, column = 1)


root = Tk()
app = App(root)
root.mainloop()

-- 
Regards,
Phil
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter + frame + grid question

2017-05-15 Thread Peter Otten
Phil wrote:

> Thank you for reading this.
> 
> I'd like to place a red frame in the centre of the main window.
> 
> I've discovered two ways to achieve this using place() and pack(padx,
> pady). Grid() does not give the desired result.
> 
> Next I'd like to place some widgets on the frame. Again place() does what
> I want and pack() almost does except the red frame is the size of the
> padding. It now seems to me that this is the way it's supposed to work.
> I'd like to use grid(), but so far, all that I can achieve is to place
> widgets on the main window and not the frame. The frame does not display
> if I use grid().
> 
> I've spent hours on this and an Internet search has not helped at all.
> However, I did learn that grid() and pack() are not compatible, could this
> be the problem? Perhaps I have to let go of the familiar grid() method and
> use pack() instead? Place() does exactly what I want but it's a bit
> cumbersome to use. The more I think about it, the more I think pack() is
> the go.
> 
> Still, I'd like to know, what's the best method?

place() is a pain if the screen or font size differs from what you expect.
I use grid() almost exclusively, but I have to admit that I always have to 
play around a bit until I get something close to what I want.

> 
> The following is a summary of what I've tried:
> 
> from tkinter import *
> 
> class App:
> 
> def __init__(self, master):
> master.geometry('400x400+50+50')
> frame = Frame(master, width = 300, height = 300, bg = 'red')
> 
> frame.pack(pady = 50)
> #frame.place(x = 50, y = 50)
> 
> 
> Entry(frame).place(x = 100, y = 100, anchor = CENTER)
> #Entry(frame).pack(padx = 20, pady = 20)
> #Entry(frame).grid(row = 10, column = 1)
> 
> #Entry2 = Entry
> #Entry2(frame).grid(row = 20, column = 1)

Columns and rows are logical columns; typically you will use 0 and 1 rather 
than 10 and 20.

> 
> 
> root = Tk()
> app = App(root)
> root.mainloop()
> 

Here's a grid()-based contender:

class App:
def __init__(self, master):
master.columnconfigure(0, weight=1)
master.rowconfigure(0, weight=1)

frame = Frame(master, bg="red")
frame.grid(row=0, column=0, padx=30, pady=30, sticky="nsew")
frame.rowconfigure(0, weight=1)

entry = Entry(frame)
entry.grid(row=0, column=0, padx=30, pady=30)


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter + frame + grid question

2017-05-15 Thread Alan Gauld via Tutor
On 15/05/17 07:11, Phil wrote:

> I'd like to place a red frame in the centre of the main window.

What do you want surrounding it?
You are going to have to use whichever layout manager
fits the scenario. Remember you can use different layout
managers in each frame in your app - and you will usually
have several frames.

Lets assume you fill your main window with a single
frame(via pack) then use a 3x3 grid inside that frame
and put your red frame in the centre cell of your
grid.

That will give you the centre red frame plus space for
8 surrounding components or frames

> ...I did learn that grid() and pack() are not compatible

I don't know what you mean by that. You can freely mix frames
with grid/pack/place layout managers but only one manager can
be used at a time per frame. So if you adopted the scheme
above the top level window uses pack() the enclosed frame
uses grid. The red frame can use place, or pack or grid
(or any of the other layout managers available, for example,
Tix provides a Form manager)

Sketching out how your frames and components will be laid
out on paper is often a good idea. That will help you decide
how many frames you need and which layout manager to use
per frame.

I rend to use a standard layout of

MainWindow
   Menubar(not allocated by layout manager0
   Frame
 single row grid for toolbar buttons
   Frame
 main grid of controls/subframes (usually
 there will be 3 or 4 subframes holding
 the actual components, these subframes
 will usually use pack())
   Frame
 status bar labels

The three top level frames are packed in the mainwindow
The top frame uses pack for the buttons(but could use
a 1 row grid instead)
The centre frame tends to use Grid(but might use Form if I'm using tix)
The bottom frame will use pack (but again, could be a single row grid)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write the __str__ function

2017-05-15 Thread Sydney Shall

On 15/05/2017 01:27, Alan Gauld via Tutor wrote:

On 14/05/17 19:03, Sydney Shall wrote:


The code that I have so far is as folows:

  def __str__(self):
 return("\n"
"   Output from __str__ of POCWP. "
"\n"
"\n After the first turnover, during the "
"'Population Of Capitals Init' cycle,"
"\n the productivities were raised from 1.0 "
"\n to a specific Unit Constant Capital (UCC) "
"for each specific capital: "
"\n The input value for the mean of UCC "
"was %7.5f" % (self.ucc),


Here endeth the first string


"\n The fractional sigma (FractionalSTD)"
" of UCC that was input was %7.5f " % (self.fractsigma_ucc))


And here the second. Returning two strings separated
by a comma makes it a tuple. Instead put the two values in a tuple at
the end of a single concatenated string.

And while at it make life easier for your self and use triple quotes:

def __str__(self):
return """
   Output from __str__ of POCWP.

After the first turnover, during the
'Population Of Capitals Init' cycle,
the productivities were raised from 1.0
to a specific Unit Constant Capital (UCC)
for each specific capital:
 The input value for the mean of UCC was %7.5f
 The fractional sigma (FractionalSTD) of UCC that was input was %7.5f
""" % ( self.ucc, self.fractsigma_ucc)

Tweak the formatting to suit.

However, I'm not sure thats really a good use of __str__,
I might be tempted to make that an explicit method that's
called pprint()  - for pretty-print - or somesuch.
__str__() methods are usually a fairly cocise depiction
of the objects state that you can embed in a bigger string.

Maybe pprint() would look like

def pprint(self):
return """
   Output from __str__ of POCWP.

After the first turnover, during the
'Population Of Capitals Init' cycle,
the productivities were raised from 1.0
to a specific Unit Constant Capital (UCC)
for each specific capital: %s""" % self

And __str__()

def __str__(self):
   return """
The input value for the mean of UCC was %7.5f
The fractional sigma (FractionalSTD) of UCC that was input was %7.5f """
% (self.ucc, self.fractsigma_ucc)

Thus pprint() uses str() to create the long version while str()
just gives the bare bones result.

Just a thought.


Here endeth the second (! -presumptious?) string.

"""I would like to thank you all for the five lessons.

The advice of course gave me several useful ways of outputting data.

I believe I now have a better understanding of output."""

Many thanks.


--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter + frame + grid question

2017-05-15 Thread Abdur-Rahmaan Janhangeer
Hum i understand your frustration. however,

whatever you use it is ok, just don't mix them at the same time.

either

use grid
or
use pack
or
use place

grid is best for me

else try some tricks here and there

like try adding  transparent images in the grid manager

use PIL module

by specifying the image sizes you place the frame where you want

a tip:
UI design is always a bit frustrating, even in Android coding, but some
tricks help like the image trick i learnt there . . . kind of hack or work
around. Coding is not straight forward but authors of languages try as much
as possible to cover the needs of users.

we just have to extend sometimes somewhere

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter + frame + grid question

2017-05-15 Thread Phil
On Mon, 15 May 2017 16:14:48 +0200
Peter Otten <__pete...@web.de> wrote:

Thank you Peter, Alan and Abdur-Rahmaan for your replies.

After a night's sleep I'm now well on the way to beautifying a Lotto checking 
program that I wrote a couple of years ago. The need for and the use of frames 
is now clearer to me now, plus I now see why I should include the use of 
columnconfigure and sticky.

I knew about tix but hadn't investigated it until now. I'll have to play with 
it.

-- 
Regards,
Phil
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Jim

On 05/15/2017 02:48 AM, Steven D'Aprano wrote:

On Sun, May 14, 2017 at 10:57:57PM -0500, Jim wrote:

I am running this on Mint 18. This is the third script I have
written to open and position windows in workspaces. The first two
work, but trying to open ebook-viewe r (calibre) with a specific
book produces the following error. If I run the same command in the
terminal it works without an error.


I think your problem is that you're telling subprocess to run a
command called:

ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub

 with no arguments. What you want is a command called:

ebook-viewer

and a single argument:

/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub

 I think (but haven't tried it) that the simplest way to fix that is
to change the entry in self.programs from:


self.programs = ['jedit', 'google-chrome', 'doublecmd',
'ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']





to:

path_to_file =
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'






self.programs = ['jedit',

'google-chrome', 'doublecmd', ['ebook-viewer', path_to_file], ]


I made the changes you suggested.

def __init__(self):
path_to_book = 
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'
self.programs = ['jedit', 'google-chrome', 'doublecmd', 
['ebook-viewer', path_to_book ]]

self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
'google-chrome':'google-chrome',
'doublecmd':'doublecmd',
'calibre-ebook-viewer': 'libprs500'}
self.open_and_move()

I noticed you have a , between the last two ]],s. I don't think you 
meant that but I tried it both ways just incase.




and see if that fixes it. (It may not be enough, or the right
approach, but at least you'll get a different error if it is wrong
:-)


Unfortunately you are correct, I did get a different error message.

Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in 
open_it

subprocess.call([self.program])
  File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1474, in _execute_child
executable = os.fsencode(executable)
  File "/usr/lib/python3.5/os.py", line 862, in fsencode
raise TypeError("expect bytes or str, not %s" % 
type(filename).__name__)

TypeError: expect bytes or str, not list

Traceback (most recent call last):
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 78, in 


Place()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in 
__init__

self.open_and_move()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 31, in 
open_and_move
p = Popen(['xdotool', 'search', '--classname', 
self.classname[self.program]], stdout=subprocess.PIPE)

TypeError: unhashable type: 'list'

Regards,  Jim



The difference is that the shell automatically splits things on
spaces, so it sees the space between ebook-viewer and the long path,
and treats the first word as the executable and the second as an
argument. But Python treats the whole string, spaces and quotes
included, as the executable.





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Jim

On 05/14/2017 11:19 PM, boB Stepp wrote:

On Sun, May 14, 2017 at 10:57 PM, Jim  wrote:

I am running this on Mint 18.
This is the third script I have written to open and position windows in
workspaces. The first two work, but trying to open ebook-viewe r (calibre)
with a specific book produces the following error.
If I run the same command in the terminal it works without an error.


Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in
open_it
subprocess.call([self.program])
  File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'

Code:

# place_windows_OO_WS3.py

import subprocess
from subprocess import Popen,PIPE
import threading
import time

class Place():

def __init__(self):
self.programs = ['jedit', 'google-chrome', 'doublecmd',
'ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']
self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
'google-chrome':'google-chrome',
'doublecmd':'doublecmd',
'calibre-ebook-viewer': 'libprs500'}
self.open_and_move()

def open_it(self):
subprocess.call([self.program])


I'm not very familiar with using the subprocess module yet, but when
the above call to "subprocess.call([self.program])" occurs, isn't
subprocess.call() expecting a list like

['ebook-viewer', '/home/jfb ...']

?

Hope I am not off-track here.

boB


Bob,

I thought you were on to something, especially since Steven suggested 
about the same thing. See my reply to Steven. It seems to be looking for 
a str or byte not a list.


Thanks,  Jim


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Jim

On 05/15/2017 07:03 AM, Peter Otten wrote:

Jim wrote:


I am running this on Mint 18.
This is the third script I have written to open and position windows in
workspaces. The first two work, but trying to open ebook-viewe r
(calibre) with a specific book produces the following error.
If I run the same command in the terminal it works without an error.


Exception in thread Thread-4:
Traceback (most recent call last):
   File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
 self.run()
   File "/usr/lib/python3.5/threading.py", line 862, in run
 self._target(*self._args, **self._kwargs)
   File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in
open_it
 subprocess.call([self.program])
   File "/usr/lib/python3.5/subprocess.py", line 557, in call
 with Popen(*popenargs, **kwargs) as p:
   File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
 restore_signals, start_new_session)
   File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
 raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer


/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'


Code:

# place_windows_OO_WS3.py

import subprocess
from subprocess import Popen,PIPE
import threading
import time

class Place():

 def __init__(self):
 self.programs = ['jedit', 'google-chrome', 'doublecmd',
 'ebook-viewer


/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']

 self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
 'google-chrome':'google-chrome',
 'doublecmd':'doublecmd',
 'calibre-ebook-viewer': 'libprs500'}
 self.open_and_move()

 def open_it(self):
 subprocess.call([self.program])

 def open_and_move(self):
 for self.program in self.programs:
 opener = threading.Thread(target=self.open_it)
 opener.start()
 time.sleep(2)
 p = Popen(['xdotool', 'search', '--classname',
self.classname[self.program]], stdout=subprocess.PIPE)

 if self.classname[self.program] == 'sun-awt-X11-XFramePeer':
 wid = str(p.stdout.read())
 wid = wid[len(wid) - 11 : len(wid) - 3]
 x = '0'
 y = '0'
 print('***jedit***')
 elif self.classname[self.program] == 'google-chrome':
 wid = str(p.stdout.read())
 wid = wid[len(wid) - 11 : len(wid) - 3]
 x = '1924'
 y = '0'
 print('***google***')
 elif self.classname[self.program] == 'doublecmd':
 wid = str(p.stdout.read())
 wid = wid[len(wid) - 11 : len(wid) - 3]
 x = '1924'
 y = '537'
 print('***double***')
 else:
 wid = str(p.stdout.read())
 wid = wid[len(wid) - 11 : len(wid) - 3]
 x = '2540' #'1924'
 y = '537'
 print('***calibre***')
 subprocess.call(['xdotool', 'windowmove', str(wid), x, y])

I did some googling and it seems that subprocess does not have a length
limit in linux. Could someone tell me how to correct the above error.


Not directly related to your question, but I think you should have one
instance of your Place class per program. That way you keep related
information together and avoid the need to look it up in a dict or find it
with a long chain of if ... elif ... tests. For example:

# untested
import subprocess
import threading
import time

DELAY = 3.0  # seconds


class Place:
def __init__(self, cmd, classname=None, name=None, x=0, y=0):
if classname is None:
classname = cmd[0]
if name is None:
name = cmd[0]

self.cmd = cmd
self.classname = classname
self.name = name
self.x = x
self.y = y

def open_it(self):
subprocess.call(self.cmd)

def open_and_move(self):
opener = threading.Thread(target=self.open_it)
opener.start()
time.sleep(DELAY)
output = subprocess.Popen(
['xdotool', 'search', '--classname', self.classname],
stdout=subprocess.PIPE
).communicate()[0]
wid = output.split()[-1].decode()
subprocess.call(
[
'xdotool', 'windowmove',
wid, str(self.x), str(self.y)
]
)
print("***{}***".format(self.name))

EBOOK = (
"/home/jfb/Documents/eBooks/Javascript/"
"GOOGLE_SHEETS/googlespreadsheetprogramming.epub"
)

programs = [
Place(["jedit"], classname="sun-awt-X11-XFramePeer"),
Place(["google-chrome"], x=1924),
Place(["doublecmd"], x=1924, y=537),
Place(
["ebook-viewer", E

Re: [Tutor] No file or directory error using subprocess and Popen

2017-05-15 Thread Jim

On 05/15/2017 08:33 PM, Jim wrote:

On 05/15/2017 02:48 AM, Steven D'Aprano wrote:

On Sun, May 14, 2017 at 10:57:57PM -0500, Jim wrote:

I am running this on Mint 18. This is the third script I have
written to open and position windows in workspaces. The first two
work, but trying to open ebook-viewe r (calibre) with a specific
book produces the following error. If I run the same command in the
terminal it works without an error.


I think your problem is that you're telling subprocess to run a
command called:

ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub


 with no arguments. What you want is a command called:

ebook-viewer

and a single argument:

/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub


 I think (but haven't tried it) that the simplest way to fix that is
to change the entry in self.programs from:


self.programs = ['jedit', 'google-chrome', 'doublecmd',
'ebook-viewer
/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub']






to:

path_to_file =
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'







self.programs = ['jedit',

'google-chrome', 'doublecmd', ['ebook-viewer', path_to_file], ]


I made the changes you suggested.

def __init__(self):
path_to_book =
'/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'

self.programs = ['jedit', 'google-chrome', 'doublecmd',
['ebook-viewer', path_to_book ]]
self.classname = {'jedit' : 'sun-awt-X11-XFramePeer',
'google-chrome':'google-chrome',
'doublecmd':'doublecmd',
'calibre-ebook-viewer': 'libprs500'}
self.open_and_move()

I noticed you have a , between the last two ]],s. I don't think you
meant that but I tried it both ways just incase.



and see if that fixes it. (It may not be enough, or the right
approach, but at least you'll get a different error if it is wrong
:-)


Unfortunately you are correct, I did get a different error message.

Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in
open_it
subprocess.call([self.program])
  File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1474, in _execute_child
executable = os.fsencode(executable)
  File "/usr/lib/python3.5/os.py", line 862, in fsencode
raise TypeError("expect bytes or str, not %s" %
type(filename).__name__)
TypeError: expect bytes or str, not list

Traceback (most recent call last):
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 78, in

Place()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in
__init__
self.open_and_move()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 31, in
open_and_move
p = Popen(['xdotool', 'search', '--classname',
self.classname[self.program]], stdout=subprocess.PIPE)
TypeError: unhashable type: 'list'

Regards,  Jim



Replying to myself to report that I got it working.
I changed open_it to:

def open_it(self):
if self.program == 'ebook-viewer':
subprocess.call([self.program, self.path_to_book])
else:
subprocess.call([self.program])

After looking at it, I realized I should be providing the path when I 
was actually opening the file in open_it not further down in 
open_and_move where I was positioning the windows. Also I realize 
open_and_move is a poor name and needs to be changed to move_it or 
something.


I still get the following error but it does not seem to effect the 
programs operation. So for now I am just glad it is working.


Traceback (most recent call last):
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 84, in 


Place()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in 
__init__

self.open_and_move()
  File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 37, in 
open_and_move
p = Popen(['xdotool', 'search', '--classname', 
self.classname[self.program]], stdout=subprocess.PIPE)

KeyError: 'ebook-viewer'

Thanks for everyones help,  Jim

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor