Open the same excel file in different windows with python - python

I am very new to python. I'm currently trying to open the same instances of one excel-file (Excel 2013) and move opened windows using python, but can't find any info on how to do it. Manually i would just click on "New Window" on "View" tab.
If I'll try open it with subprocess, it'll successively open and close windows.
Have you got any suggestions?
Thanks in advance.
My current code:
import ctypes
import subprocess
import time
import sys
from win32.win32gui import FindWindow, MoveWindow, GetForegroundWindow
user32 = ctypes.windll.user32
x = user32.GetSystemMetrics(78)
y = user32.GetSystemMetrics(79)
p1 = subprocess.Popen(["C:\\Program Files (x86)\\Microsoft Office\\Office15\\EXCEL.EXE", "C:\\Users\\user\\Desktop\\python\\TestBook1.xlsx"])
time.sleep(1)
window_handle1 = GetForegroundWindow()
MoveWindow(window_handle1, 0, 0, int(2/3*x), int(0.5*y), True)
p2 = subprocess.Popen(["C:\\Program Files (x86)\\Microsoft Office\\Office15\\EXCEL.EXE","C:\\Users\\user\\Desktop\\python\\TestBook1.xlsx"])
time.sleep(1)
window_handle2 = GetForegroundWindow()
MoveWindow(window_handle2, 0, int(0.5*y), int(2/3*x), int(0.5*y), True)
p3 = subprocess.Popen(["C:\\Program Files (x86)\\Microsoft Office\\Office15\\EXCEL.EXE", "C:\\Users\\user\\Desktop\\python\\TestBook1.xlsx"])
time.sleep(1)
window_handle3 = GetForegroundWindow()
MoveWindow(window_handle3, int(2/3*x), 0, int(1/3*x), int(y), True)
(sorry for my bad coding in advance)

I don't know python, so likely to be garbage code!
Using the Excel COM object you get programmatic access to the "new window" (among other things).
The Window object that is returned from Workbook.NewWindow has a hWnd property (which might be what you need for the MoveWindow) and/or there is also a Top and Left property you can use to move the window too.
import win32com
import win32com.client
app = win32com.client.Dispatch("Excel.application")
workbook = app.Workbooks.Open("your workbook")
newwindow = workbook.NewWindow()
MoveWindow(newwindow.hwnd,.......)

Related

Cannot click on tkinter button more than twice

I am a newbie to tkinter and have know idea what I am doing sometimes:D . I created a python script to get Corona Virus Stats from a GitHub post link The script has over 20 files in it so I thought I should just create one file to run all the other files. So what other better way to do it than creating a UI. And that's what I did I used tkinter to run all the files. If they clicked on x button then I would run abc. And I ended up running these files by importing them in a certain order(Don't know If that was the best way). So here is where I ran into an error. I don't exactly know if this error is because of how I imported my files or my tkinter code is just wrong. I just couldn't seem to click on a button twice. I would run my program and click on a button, it would run properly and then the next time I clicked on that same button It would just not work. There was no error and no output. Nothing would happen. Here is my code:
#Import tkinter
import tkinter as tk
from tkinter import *
from tkinter import simpledialog
tk = tk.Tk()
Max = 190
def RunDeaths():
#If they click on RunDeaths I will run this function
#Check if they have already entered a path
try:
open('/Users/test/Documents/python/Py_Programs/Hackathon/DeathStats/Info.txt','r')
from DeathStats import RunAll
except:
YourPath = simpledialog.askstring('Countries','''Please Enter Your Path To HACKATHON Folder:
Example:
\"/Users/Name/Documents/python/\"
Note: Leave out the HACKATHON folder and you must put a slash at the end''',parent=tk)
#Write this path to a file call Info.txt
file = open('/Users/test/Documents/python/Py_Programs/Hackathon/DeathStats/Info.txt','w')
file.write(str(YourPath)+'\n')
file.write(str(Max))
file.close()
#Run all the files that gather the data for Corona Virus Deaths
from DeathStats import RunAll
def RunRecoveredCases():
#If they click on RecoveredCases Run this
#Check If they had already entered a path
try:
open('/Users/test/Documents/python/Py_Programs/Hackathon/RecoveredCases/Info.txt','r')
from RecoveredCases import RunAll
except:
YourPath = simpledialog.askstring('Countries','''Please Enter Your Path To HACKATHON Folder:
Example:
\"/Users/Name/Documents/python/\"
Note: Leave out the HACKATHON folder and you must put a slash at the end''',parent=tk)
file = open('/Users/test/Documents/python/Py_Programs/Hackathon/RecoveredCases/Info.txt','w')
#Write there path to a file
file.write(str(YourPath)+'\n')
file.write(str(Max))
file.close()
#Run all the files that gather all the Recovered Cases
from RecoveredCases import RunAll
#* * Here is where I think I went wrong But Im not sure
Deaths = Button(tk,height = 20, width = 30, text='Run Deaths',command = RunDeaths,highlightbackground='#000000')
Recovered = Button(tk,height = 20, width = 30, text='Run Recovered Cases',command = RunRecoveredCases,highlightbackground='#000000')
Deaths.pack()
Recovered.pack()
tk.mainloop()
So my question and problem is: Why can I not click on a button more than twice?
This has happened to me before and I could not fix it. Any help would be appreciated.(If you would like to run my program because my explanation was just not good enough here is a git hub repo GitHub)
Thank You
It appears that you are assuming that from RecoveredCases import RunAll will run the code in RecoveredCases.py each time it is imported. That is a false assumption. Python caches code that is imported.
The proper way to use code in a separate file is to put the code in a function or class, import the function or class exactly once, and then call the function or instantiate the class whenever you want to run the code.

Pythons Webbrowser Module Will Never Open a Link in a new Window

I was trying to automate opening multiple user profiles given a list of names on a few different sites but i can not find a way to open a link in a new window meaning i can not sort the different sites i am opening into their own window collection.
here is my code:
import webbrowser
chrome_path="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
firefox_path="C:\\Program Files\\Mozilla Firefox\\Firefox.exe"
strURL = "http://www.python.org"
webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path),1)
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(chrome_path),1)
webbrowser.open(strURL, new=0)
webbrowser.open(strURL, new=1)
webbrowser.open(strURL, new=2)
webbrowser.get('chrome').open(strURL)
webbrowser.get('firefox').open(strURL)
webbrowser.get('chrome').open_new(strURL)
webbrowser.get('firefox').open_new(strURL)
no matter what value i put for new (0, 1, or 2), all that ever happens is it opens a new tab in the last window i clicked on. i have tried all of the other methods that i found in they python documentation for the webbrowser module and everyone online is just saying to use "new=1" or webbroswer.open_new() but neither of those work. and even when i point it at firefox it just goes to chrome.
P.S.
i found a small workaround that i am not totally satisfied with.
import webbrowser
chrome_path = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
chrome_path_NW = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s --new-window"
firefox_path = "C:\\Program Files\\Mozilla Firefox\\Firefox.exe"
strURL = "http://www.python.org"
controller = webbrowser.get(chrome_path)
controllerNW = webbrowser.get(chrome_path_NW)
controllerNW.open(strURL, new=0)
controller.open(strURL, new=1)
controller.open(strURL, new=2)
controller.open("www.youtube.com", new=2)
the important thing to look at would be the "chrome_path" variable. i have changed it so it will run as a command and accept arguments. i found some launch arguments for chromium, here, that seem to work from chrome too. "--new-window" will open a new window and i can then open more tabs in that window but this is a total workaround of pythons module that i am not confident won't break if i am trying to use chrome while running this script. if there is any feature where i could group links together to open in specific windows that would be much more useful to me.
I realise this is a bit late but hopefully i can help someone in the future.
Basically you need to use the subprocess module to open up a new window before you load a new webpage
import subprocess
import time
import webbrowser
subprocess.Popen('open -a /Applications/Google\ Chrome.app --new', shell=True)
time.sleep(0.5) # this is to let the app open before you try to load a new page
webbrowser.open(url)

import python module when launching from VBA

It is the first time I write as I really didn't find any solution to my issue.
I want to allow my user to launch some Python program from Excel.
So i have this VBA code at some point:
lg_ErrorCode = wsh.Run(str_PythonPath & " " & str_PythonArg, 1, bl_StopVBwhilePython)
If lg_ErrorCode <> 0 Then
MsgBox "Couldn't run python script! " _
+ vbCrLf + CStr(lg_ErrorCode)
Run_Python = False
End If
str_PythonPath = "C:\Python34\python.exe C:\Users\XXXX\Documents\4_Python\Scan_FTP\test.py"
str_PythonArg = "arg1 arg2"
After multiple testing, the row in error in Python is when I try to import another module (I precise that this VBA code is working without the below row in Python):
import fct_Ftp as ftp
The architecture of the module is as follow:
4_Python
-folder: Scan_FTP
- file: test.py (The one launch from VBA)
-file: fct_Ftp.py
(For information, I change the architecture of the file, and try to copy the file at some other position just to test without success)
The import has no problem when I launch Test.py directly with:
import sys, os
sys.path.append('../')
But from VBA, this import is not working.
So I figured out this more generic solution, that dont work as well from Excel/VBA
import sys, os
def m_importingFunction():
str_absPath = os.path.abspath('')
str_absPathDad = os.path.dirname(str_absPath)
l_absPathSons = [os.path.abspath(x[0]) for x in os.walk('.')]
l_Dir = l_absPathSons + [str_absPathDad]
l_DirPy = [Dir for Dir in l_Dir if 'Python' in Dir]
for Dir in l_DirPy:
sys.path.append(Dir)
print(Dir)
m_importingFunction()
try:
import fct_Ftp as ftp
# ftp = __import__ ("fct_Ftp")
write += 'YAAAA' # write a file YAAAA from Python
except:
write += 'NOOOOOO' # write a file NOOOOO from VBA
f= open(write + ".txt","w+")
f.close()
Can you please help me as it is a very tricky questions ?
Many thanks to you guys.
You are able to start your program from the command line?
Why not create a batch file with excel which you then start in a shell?

Is it possible to use win32com in python script for GIMP

I try to use win32com in GIMP python script.
Script should appear under tab: /Grzegorz.
I noticed that "IMPORT FROM EXCEL..." shortcut appears on tab only when I delete import declaration "import win32com.client as win32". So I assume win32com causes problem.
Win32com works when I try it outside gimp as a python file so win32com is ok.
#!/usr/bin/env python
from gimpfu import *
import win32com.client as win32
def import_text_my(img):
Excel = win32.gencache.EnsureDispatch("Excel.Application")
Excel.Visible = True
title = Excel.ActiveSheet.Cells(Excel.Selection.Row, 1).Value
description = Excel.ActiveSheet.Cells(Excel.Selection.Row, 1).Value
param = pdb.gimp_image_get_active_layer(img)
ret = param.Split(" ")
if len(ret) == 1:
ret = [title, title, 'textZwyklyLeft']
output = param.replace(ret[1], title)
layerMy = img.active_layer
layerMy.Name = output
pdb.gimp_text_layer_set_text(layerMy, description)
register(
"python_import_excel",
"IMPORT FROM EXCEL",
"import_text",
"Grzegorz Mackiewicz",
"Grzegorz Mackiewicz",
"2019",
"IMPORT FROM EXCEL...",
"",
[
(PF_IMAGE, "img", "Input image", None)
],
[],
import_text_my, menu="<Image>/Grzegorz")
main()
Does anyone know if there is possiblility to use win32com in gimp script?
pypiwin32Yes, but you would have to add the win32com module to the python runtime used by Gimp.
Some indications to install things here (this is for numpy, but holds for anything installed with PIP).
This post hints that you should install pypiwin32 with PIP.

Change wallpaper in Python for user while being system

what I am trying to do is change the desktop wallpaper in windows.
To do that, I use the following code:
import ctypes
import Image
pathToBmp = "PATH TO BMP FILE"
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, pathToBmp , 0)
this works when I run the .py file, this works when I convert it using py2exe and run the exe under the current user, but when I run the exe as SYSTEM, the current user background does not change.
This ofcourse was to be expected. But I don't know how to solve it.
By the way, it does not matter if any of your solutions changes the current user background or all the users' backgrounds.
Thank you for your time.
How about creating a value key in the registry at:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
This will change the background when ever the user login.
To try it, write this script, name it for example SetDesktopBackground.py, any where you like:
#!python
from ctypes import *
from os import path
SPI_SETDESKWALLPAPER = 0x14
SPIF_UPDATEINIFILE = 0x1
lpszImage = path.join(path.dirname(path.realpath(__file__)), 'your_image.jpg')
SystemParametersInfo = windll.user32.SystemParametersInfoA
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, lpszImage, SPIF_UPDATEINIFILE)
Dont forgot to put some image, your_image.jpg, in the same directory. Then open the registery editor:
Start > Search > type regedit.exe
Then go to the path:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
Right click and choose New > String Value and type any name you like for this value.
Right click on this new value and choose Modify, in the Data Value field write:
"C:\Python26\pythonw.exe" "C:\Path\To\SetDesktopBackground.py"
To test it, logout and login again. The background should change when ever this user login.
That was the manual way to do it, you can use _winreg in your application to create the value during the installation:
#!python
from _winreg import *
from sys import executable
from os import path
subkey = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
script = 'C:\\Path\\To\\SetDesktopBackground.py'
pythonw = path.join(path.dirname(executable), 'pythonw.exe')
hKey = OpenKey(HKEY_CURRENT_USER, subkey, 0, KEY_SET_VALUE)
SetValueEx(hKey, 'MyApp', 0, REG_SZ, '"{0}" "{1}"'.format(pythonw, script))
CloseKey(hKey)

Categories

Resources