Python selenium how to make python to take the next notepad - python

I'm making a python script that will automatically post to Instagram. It's a skateboarding niche page and I want to give credit to people I repost... (I'm posting thrue facebook creator studio)
This is how the video picker looks like...
skatenr = int(skatenr) + int("1")
SendKeys = "C://Users/User/PycharmProjects/skateboard auto post/skate/"+str(memenr)+".mp4"
driver.find_element_by_xpath('/html/body/div[6]/div/div/div/div/div/a/div[2]/input').send_keys(SendKeys)
You could see how I got it to take the next post from the folder I store my vids in. My idea was that I store the captions in another folder and name it skate1.txt skate2.txt ...... then like the videos it takes the notepad and puts it in the caption place. How do I make Python pick the next notepad.
def read_line():
f = open('skate1.txt')
The = (f.read())
return The
print(read_line())
any ideas?
Regards your friendly guy who started coding yesterday

if you run the code at all time you can use this formular
from os import path
x=0
The=[]
while path.exists('skate%s.txt'%str(x)):
with open("skate%s.txt"%str(x),'r') as file:
k=file.read()
The.append(k)
x+=1
now all of your caption will be in the "The" list

Related

Create a page using Pywikibot

I am trying to create a page in https://dev.wikidebates.org/wiki/Wikidébats:Accueil, it is similar ti wikipedia, so Pywikibot should work the same way. I would like to make a page using Pywikibot. I checked option scripts in Pywikibot https://www.mediawiki.org/wiki/Manual:Pywikibot/Scripts. The script pagefromfile.py is responsible for it. However, I don't see in the code where I should write link on new page of wiki.
Also function inter in class Pagefromfile returns page. How can I check that the page was made?
The code which I try now is the following. Everything works ok, except last line.(Page is not created)
site = pywikibot.Site('dev', 'wikidebates') # The site we want to run our bot on
page = pywikibot.Page(site, "Faut-il légaliser le cannabis ?")
text = page.get() #get the code of the page
wb = open("pages1.txt", "w", encoding="utf-8")
wb.write(str(txt)) #write text to the file, in order to download it then to the wiki
wb.close()
main_page('-file:pages1.txt') #use main function from scrip pagefromfile.py - I renamed it
You haven't shown any further information. Probably there are any further messages from pagefromfile.py script. If you download the text from a wiki you either have to include begin and end markers to the text or you have to use the -textonly option. I also propose to use the -title option.
Refer the doc: https://doc.wikimedia.org/pywikibot/stable/scripts/general.html#module-scripts.pagefromfile
from scripts.pagefromfile import main # or main_page in your modified case
site = pywikibot.Site('wikidebates:dev') # you may use te site name for the constructor function
page = pywikibot.Page(site, 'Faut-il légaliser le cannabis ?')
text = page.text
with open("pages1.txt", "w", encoding="utf-8") as wp: # also closes the file
wb.write(text)
main('-file:pages1.txt', '-textonly', '-title:"The new title"')
To specify the target site, add a -site option to the main function if it is not your default site. For simulating purpose you can use the -simulate option:
main('-file:pages1.txt', '-textonly', '-title:"The new title"', '-simulate', '-site:wikidebates:dev')
Note: all arguments given to the main function must be strings delimited by comma. You cannot give all arguments as a long string except you do it like this:
main(*'-file:pages1.txt -textonly -title:The_new_title'.split())

How to focus on a window with python?

I'm writing a python code that allows a user to mark text from a website and then paste it into a word document. I'm using pyautogui and win32clipboard.
So here is the flow-
1. the user finds an interesting line on a website.
2. the user marks the desired text.
3. the user runs the python script ( I don't want python to run all the time, only when asked).
4. python uses pyautogui to copy the text (ctrl + c) and then win32clipboard.
5. python writes the copied text to a doc file.
As for now, the only problem I have is in the transition from 3 to 4.
The issues are-
a) when I try to run the python from cmd, ctrl c hotkey makes the script stop (keyboard interrupt). How can I overcome that?
b) how can I make the script run on the current website? how do I return the focus to that window? as for now, I'm running the script within Pycharm and it works, but I want it to run in the "outside world"!
Thanks in advance,
Karin :-)
P.S- this is the code I'm trying to run.
--getting the url
pyautogui.hotkey("Ctrl","f")
time.sleep(.01)
pyautogui.hotkey("Ctrl","c")
time.sleep(.01)
win32clipboard.OpenClipboard()
url = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
--- getting the marked text
pyautogui.hotkey("Ctrl","c")
time.sleep(.01)
win32clipboard.OpenClipboard()
text = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
Well, after a lot of research, I found a very simple solution for the problem- using time.sleep(). During that time the user can switch to the desired window and the code works fine :-)
You can also use
pyautogui.hotkey("alt","tab") time.sleep(.1)

How to write OS X Finder Comments from python?

I'm working on a python script that creates numerous images files based on a variety of inputs in OS X Yosemite. I am trying to write the inputs used to create each file as 'Finder comments' as each file is created so that IF the the output is visually interesting I can look at the specific input values that generated the file. I've verified that this can be done easily with apple script.
tell application "Finder" to set comment of (POSIX file "/Users/mgarito/Desktop/Random_Pixel_Color/2015-01-03_14.04.21.png" as alias) to {Val1, Val2, Val3} as Unicode text
Afterward, upon selecting the file and showing its info (cmd+i) the Finder comments clearly display the expected text 'Val1, Val2, Val2'.
This is further confirmed by running mdls [File/Path/Name] before and after the applescript is used which clearly shows the expected text has been properly added.
The problem is I can't figure out how to incorporate this into my python script to save myself.
Im under the impression the solution should* be something to the effect of:
VarList = [Var1, Var2, Var3]
Fiele = [File/Path/Name]
file.os.system.add(kMDItemFinderComment, VarList)
As a side note I've also look at xattr -w [Attribute_Name] [Attribute_Value] [File/Path/Name] but found that though this will store the attribute, it is not stored in the desired location. Instead it ends up in an affiliated pList which is not what I'm after.
Here is my way to do that.
First you need to install applescript package using pip install applescript command.
Here is a function to add comments to a file:
def set_comment(file_path, comment_text):
import applescript
applescript.tell.app("Finder", f'set comment of (POSIX file "{file_path}" as alias) to "{comment_text}" as Unicode text')
and then I'm just using it like this:
set_comment('/Users/UserAccountName/Pictures/IMG_6860.MOV', 'my comment')
After more digging, I was able to locate a python applescript bundle: https://pypi.python.org/pypi/py-applescript
This got me to a workable answer, though I'd still prefer to do this natively in python if anyone has a better option?
import applescript
NewFile = '[File/Path/Name]' <br>
Comment = "Almost there.."
AddComment = applescript.AppleScript('''
on run {arg1, arg2}
tell application "Finder" to set comment of (POSIX file arg1 as alias) to arg2 as Unicode text
return
end run
''')
print(AddComment.run(NewFile, Comment))
print("Done")
This is the function to get comment of a file.
def get_comment(file_path):
import applescript
return applescript.tell.app("Finder", f'get comment of (POSIX file "{file_path}" as alias)').out
print(get_comment('Your Path'))
Another approach is to use appscript, a high-level Apple event bridge that is sadly no longer officially supported but still works (and saw an updated release in Jan. 2021). Here is an example of reading and setting the comment on a file:
import appscript
import mactypes
# Get a handle on the Finder.
finder = appscript.app('Finder')
# Tell Finder to select the file.
file = finder.items[mactypes.Alias("/path/to/a/file")]
# Print the current comment
comment = file.comment()
print("Current comment: " + comment)
# Set a new comment.
file.comment.set("New comment")
# Print the current comment again to verify.
comment = file.comment()
print("Current comment: " + comment)
Despite that the author of appscript recommends against using it in new projects, I used it recently to create a command-line utility called Urial for the specialized purpose of writing and updating URIs in Finder comments. Perhaps its code can serve as an an additional example of using appscript to manipulate Finder comments.

Trouble with Python: Opening an app/saving a file

I am a bit new to coding, I am trying to improve my skills. My preferred programming language is python. But I do need help with this bit of code. I am making an app called User Helper for my own use. I know that the code may look a bit sloppy, but when I posted it in for some reason I put four spaces in but it didn't turn to a block of code, so I had to manually put in the spaces.
But back to the topic at hand, my code has 2 problems (though you could probably find more.) I am not able to save my favorites to a document for later use when I open the app again. As well I don't know the code to open an app from python code.
I have tried many different methods including using the os function. I think I may need some sort of directory, but I'm sorry to say I am unfamiliar with directories and I have had trouble with them. The time function will be used later in the project. And for some reason when I run this program, it tries to find a path from the folder all my coding projects are in.
I also want to thank you for reading this, and I hope I can get this solved soon. I plan to become an active member in this community, and I can't wait to continue improving my skills in coding.
Thank you for your time!
import os
import time
def name():
print ""
print ""
print "Welcome to User Helper!"
name1 = raw_input("What is your name? ")
print ""
print "Welcom to User helper "+name1+"!"
def favorites():
print ""
print "Now opening Favorites settings..."
fav1 = raw_input("Favorite 1: ")
fav2 = raw_input("Favorite 2: ")
fav3 = raw_input("Favorite 3: ")
fav1full = fav1+".app"
fav2full = fav2+".app"
fav3full = fav3+".app"
fav1_path = os.path.abspath(fav1full)
fav2_path = os.path.abspath(fav2full)
fav3_path = os.path.abspath(fav3full)
os.system(fav1_path)
name()
favorites()
You can use os.chdir() to change default directory and os.startfile() to open the program or file directly. As for saving it for later use, if you want to save it to a text file, I'll include it in my answer.

Problem with exiting a Word doc using Python

This is my first time using this so be kind :) basically my question is I am making a program that opens many Microsoft Word 2007 docs and reads from a certain table in that document and writes that info to an excel file there is well in excess of 1000 word docs. I have all of this working but the only problem when I run my code it does not close MSword after opening each doc I have to manually do this at the end of the program run by opening word and selecting exit word option from the Home menu. Another problem is also if a run this program consecutively on the second run everything goes to hell it prints the same thing repeatedly no matter which doc is selected I think this may have to do with how MSword is deciding which doc is active e.g. is it still opening the last active document that was not closed from the last run. Anyways here is my code for the opening and closing part I wont bore you guys with the rest::
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = 0
# Open a specific file
#myWordDoc = tkFileDialog.askopenfilename()
MSWord.Documents.Open("C:\\Documents and Settings\\fdosier" + chosen_doc)
#Get the textual content
docText = MSWord.Documents[0].Content
charText = MSWord.Documents[0].Characters
# Get a list of tables
ListTables = MSWord.Documents[0].Tables
------Main Code---------
MSWord.Documents.Close
MSWord.Documents.Quit
del MSWord
Basically, Python is not VBA, so this:
MSWord.Documents.Close
is equivalent to:
getattr(MSWord.Documents, "Close")
i.e. you just get some method object and do nothing with it. You need to call the method with the call operator (the parentheses :) :
MSWord.Documents.Close()
Accordingly for .Quit.
Before your MSWord.Quit did you try using:
MSWord.ActiveWindow.Close
Or even more simpley just doing
MSWord.Quit
I dont really understand if you are trying to close a document or the application.
I think you need a MSWord.Quit at the end (before and/or instead of the the del)

Categories