i get the file location from the text document but the program opens and closes immediately it won't open at all how can i fix this.
Is it because the problem is launcher.exe?
Example
file = open("fihrist.txt", "r")
read = file.readline()
os.startfile(read)
the code is an example, it was written in the same logic
Text file example
Text file [C:\Sobee\Game\launcher.exe]
The method os.startfile() only starts an application it doesn't wait for the program to close.
If you want to run code after the program has ended you could try something like this: Python subprocess: Open a program and wait for user to save and close it
Related
This is my first post on StackOverflow. I'm also a beginner in Python. So I was just tinkering with the open() function, I was making a simple program to replace text in other .txt files. Here is my code:
f = open("file.txt", "r+")
f.truncate(0)
f.write("This text has been replaced.")
f.close()
print("Text replaced")
So, after running this program, the text in "file.txt" is getting changed. However, when I do ctrl + z, it's showing Undo Reload from Disk?, and when you click OK, the text gets back to normal.
How to prevent this? I am using Python 3.9, Pycharm code editor.
Thank you
I think your question might be more about the PyCharm UI editor.
If I understand correctly:
you have "file.txt" open in the PyCharm editor
you run the code above
At this point, the filesystem has the "file.txt" with the updated contents. The PyCharm editor (buffer) still has the old contents.
When you ctrl+z, PyCharm notices the filesystem has been updated and prompts to see how you want to proceed. When you click "OK", PyCharm writes its buffer to the file, which is the original contents.
I would like to get the text from a program with Python, for example from notepad. Can I "request" this text, just like from a website? I thought about something like this:
A document in Notepad:
Hello World!
This is a text!
GetText.py:
get_text("notepad.exe")
>>> Hello World!\nThis is a text!
Is this possible?
No, you can't, not directly.
There are various accessibility, etc. APIs you could use to try and "read" the user interface of another program, but that's certainly a lot more involved than just a simple get_text() style call.
(And for Windows Notepad, you can enumerate the Notepad main window's child windows, find the edit/rich-text control it's using and send a WM_GETTEXT message (if my memory serves) and hope it sends you some of the current text back...)
You can open the file in read-mode and simply print each line of the file using a for loop:
a_file = open('notepad.exe', 'r')
for line in a_file:
print(line)
a_file.close() #Make sure you close whatever file you open
If you are using Jupyter Notebook, make sure notepad.exe is in the same directory as you have your notebook opened in.
Side note: If you have experience with the command line (e.g. Linux), you can also open it in a text editor like vim. There, you can more readily see and edit it.
I'm using VBA on Excel to run a Python script. Here's what my module looks like:
Sub PythonButton()
RetVal = Shell("C:\Python27\python.exe C:\Users\myName\Desktop\test.py", 1)
End Sub
My command window opens up and appears to give some feedback but the window only remains for a split second. How do I get this window to stay open until, say, the user presses a key?
I ended up using a batch file with a "pause" in it instead:
Sub PythonButton()
RetVal = Shell("C:\Users\myName\Desktop\start.bat", 1)
End Sub
I let my batch file run the python script instead.
I'm opening and archiving Visio files.
visio = comclt.Dispatch("Visio.Application")
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Microsoft Visio")
for i in os.listdir(path): #loops through the path
if i[-3:]=='vsd': #checks to see if it is a visio file
doc = visio.Documents.Open(path+'\\'+i)
But when I open certain Visio files, because the visio file was created on a different machine where a local stencil was present, there is an error of .vss is part of workspace but cannot be opened. This is not a problem, I can just hit ok. So I've put in code to send key ENTER.
Here is my problem. I have the code below. But it does't work because (I think) the code pauses on doc = visio.Documents.Open(path+'\\'+i) and does not continue until ok is pressed. Once I press ok manually, the code sleeps for 2 seconds before continuing.
time.sleep(2)
wsh.AppActivate("Microsoft Visio")
wsh.SendKeys("{ENTER}")
how do I tell python to not wait for doc = visio.Documents.Open(path+'\\'+i)? or is another way to solve this?
You can try to use .AlertResponse to prevent message boxes in Visio:
http://msdn.microsoft.com/en-us/library/office/ff767782.aspx
i.e. before opening the diagram, set
Visio.AlertResponse = 1
This should prevent the message from popping up.
I have a Python application taht will be executed repeatedly. It saves a PDF as a file and then prints it. When printing ends it deletes the file.
My current solution (for the print and delete part) is this:
win32api.ShellExecute(0, "print", file_path, None, ".", 0)
time.sleep(10)
os.remove(self.options.dest_name)
time.sleep(10) is a trick to give the printing process the time to run before file deletion. Without it Acrobat Reader opens (it opens anyway) and alerts that it can't find the file. This because file removal has already occured.
The question is:
how can I do it without this unreliable trick? The best thing would be to have an handler for the printing process and get by it an info about the printing state: I wait for it to report it's completed and I delete the file.
it would be even better if Acrobat Reader wouldn't open, but this is not a great problem.
EDIT: I tried switching to Foxit Reader as the default PDF reader and now it doesn't open when I don't want. ;)
OTHER POSSIBLE SOLUTION:
Cylically check if the file is available (not used by another process) and when it's available again delete it. How could I do it in Python?
At last I've found a good solution, thanks to this answer (and also #Lennart mentioned it on a comment):
install Ghostscript
install GSview (which includes gsprint.exe)
write this code:
file_path = "C:\\temp\\test.pdf"
p = subprocess.Popen(["C:\\Ghostgum\\gsview\\gsprint.exe", "-printer", printer_name, "-colour", file_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate() # waits for the gs process to end
os.remove(file_path) # now the file can be removed
No Acrobat windows opening, no file removed before printing... The annoyance: installing GS.
See also: gsprint reference
Rather than hard-coding a filename and printing that, you should use the tempfile module to create a temporary file with a unique name.
import tempfile
file_name = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
If you want, you can run a regular tidy-up script using Window's scheduling tools to delete the files created.
Adobe acrobat has (or at least used to have) a parameter "/t", which made it open, print and exit. By using it, you can call acrobat reader and wait for it to exit, and then delete the file.
Untested code:
>>> import subprocess
# You will have to figure out where your Acrobate reader is located, can be found in the registry:
>>> acrobatexe = "C:\Program Files\Adobe\Acrobat 4.0\Reader\AcroRd32.exe"
>>> subprocess.call([acrobatexe, "/t", tempfilename, "My Windows Printer Name"])
>>> os.unlink(tempfilename)
Something like that.
If you don't want acrobat to open, there are open source software that will print pdfs from the command line. You could include one with your software.
Why not use os.system, which will wait until the process is finished?