I have been working on an automation script which includes shutting down my Windows 10 pro machine.
Here is one Python code which turned to exe file
import os
import time as t
import re
while True:
To check for "sd" in a file
lst = os.listdir("attachments")[-1]
with open(f"attachments\\{lst}", "r") as f:
message = f.read()
x = re.search("sd", message)
if "sd" is found then the file must be deleted and the computer must be shut down
if x:
print("YESSSS")
os.remove(f"attachments\\{lst}")
os.system("shutdown /s /t 1")
t.sleep(5)
The problem is that after deleting the file instead of shutting down the PC the cmd.exe appears on my screen...idk its weird
click for the image
to check if the exe format didnt have any problems i created another exe file
here is the code
import os
os.system("shutdown /s /t 1")
Turns out there is nothing wrong with the exe format...it performs normal shutdown....god just doesn't like me
Please help me 🥺
Related
from datetime import date
bugun = str(date.today())
if bugun == "2021-04-25":
with open("dosya.py","r+") as dosya:
liste = dosya.readlines()
liste.insert(3,"DenemeBu\n")
del liste[4]
dosya.seek(0)
print(liste)
with open("dosya.py","w") as dosya:
for i in liste:
dosya.write(i)
import os
print("Hello")
sayi1 = int(input("Sayi1: "))
sayi2 = int(input("Sayi2: "))
print("Sonuc {}".format(sayi1+sayi2))
I want to change second file with first file but I want first file to open when my pc opens and takes current date. When date corrects and changes second file.
Open your startup folder by pressing Win + R and typing in shell:startup
Within this folder, create a txt file and rename it to anything.bat and edit it with
#ECHO OFF
python3 C:/path/to/my/script.py
You can remove the "#ECHO OFF" if you want it to have a terminal window popup.
EDIT: As for the error you're facing.
Change
open("dosya.txt", "r")
to
open("C:/full/path/to/dosya.txt", "r")
Do that everywhere you open dosya.txt, like at the dosya.txt write below
You're facing this error because you're running the command for the script from a directory that doesn't contain that file and it tries to find that file in it's running directory and can't find it. Setting the full path to it will make the script work if run from any directory on your computer.
I have written a script that can auto-run any script when PC starts
import os
import winreg
class is_at_startup:
'''Adding the given program path to startup'''
def __init__(self, program_path):
self.program_path = program_path
self.program_basename = os.path.basename(self.program_path)
def main(self):
'''Adding to startup'''
if os.path.exists(self.program_path):
areg = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
try:
akey = winreg.OpenKey(areg, f'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\{self.program_basename}', 0, winreg.KEY_WRITE)
areg.Close()
akey.Close()
print(f'{self.program_path} already at startup')
except WindowsError:
key = winreg.OpenKey(areg, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 0, winreg.KEY_SET_VALUE)
winreg.SetValueEx(key, f'{self.program_basename}', 0, winreg.REG_SZ, f'{self.program_basename}')
areg.Close()
key.Close()
print(f'{self.program_path} added to startup')
if __name__ == '__main__':
startup = is_at_startup('your program path')
startup.main()
If you are using python 2.7.x then replace winreg with _winreg
I have tried this way for .bat files, and it worked you can also try. Put your python files that you want to run on windows startup at this location.
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
I want my python file to run if Windows is booted up every single time, so I used this simple code:
Background.py (This creates a .bat file which will run my desired .py file on every windows startup)
import getpass
import os
USER_NAME = getpass.getuser()
def add_to_startup():
bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME
with open(bat_path + '\\' + "open.bat", "w+") as bat_file:
bat_file.write(r'C:\Users\intel\AppData\Local\Programs\Python\Python38\python.exe C:\Users\intel\Desktop\Python programs\testing.py %*')
add_to_startup()
And this is the .py file which I want to run every time:
with open(r"C:\Users\intel\Desktop\hello.txt", "w+") as test_file:
test_file.write(r'start')
But it's not working even if my computer is on :(
Edit 1:
I checked The startup folder also and the open.bat file is successfully created and existing...
(You can even check in the image)
enter code here
I have two files, one bell.mp3 one main.py file, that plays back bell.mp3 via subprocess.
If I do:
pyinstaller main.py
the Dist file ends up correctly, and everything works fine, The program runs in a directory.
This is the code for my file which i call pyinst_tester.py
it creates a text file, and plays a bell.mp3 file
#
from con import * # this is just a configuration file that has g='play' in it.
import subprocess
f=open(r'/home/godzilla/Desktop/Pyinstaller testing/testfile1','w')
f.write('This has worked')
f.close()
file='/home/godzilla/Desktop/Pyinstaller testing/data/bell.mp3'
if 'play' == g:
subprocess.call(['/usr/bin/cvlc',file])
a single file is created, but if I delete the bell.mp3 file it doesn't work. In a single file isn't the bell.mp3 zipped inside the main.exe ? therefore, redundant as a separate file ?
What Is the point having a single file exe, if you need an adjacent file with all the mp3s inside?
Pyinstaller has many features and if you want to include non python files (for example mp3 files) you have to do so explicitly with the --add-binary switch.
In one file mode the executable will be unpacked into a temporary directory prior to execution of the python code.
So how to write your code to access these data files.
You might want to look at the pyinstaller documention at following sections:
https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#run-time-information
https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#using-sys-executable-and-sys-argv-0
I personally place all my files in a separate directory. e.g. data.
If you place the file bell.mp3 in the directory data, then you had to call pyinstaller with the option --add-binary data:data
in the one file mode the executable is extracted into a temporary directory
whose path you get get from the variable sys._MEIPASS
Your data directory will bi in the sub directory data of sys._MEIPASS
In my example I create a function, that will be able to locate the data files in normal python mode and in pyinstaller one file or one directory mode.
Just try it out it should be self explaining
simple example:
minitst.py
import os, sys
import time
is_frozen = getattr(sys, "frozen", False)
MYDIR = os.path.realpath(os.path.dirname(__file__))
def data_fname(fname):
if is_frozen:
return os.path.join(sys._MEIPASS, "data", fname)
else:
return os.path.join(MYDIR, "data", fname)
def main():
print("This application is %s frozen" %
("" if is_frozen else "not"))
print("executable =", sys.executable,
"File =", __file__,
"mydir =", MYDIR)
if is_frozen:
print("MEIPASS", sys._MEIPASS)
fname = data_fname("tst.txt")
print("will open", fname)
with open(fname) as fin:
print(fin.read())
time.sleep(5) # this shall allow to view the console e.g. on windows if clicking on the executable.
if __name__ == "__main__":
main()
now create a directory data and place a file "tst.txt"
data/tst.txt
Hello world
Now call
pyinstaller -F minitst.py --add-binary data:data -c
and call dist/minitst from a console.
The output should look like:
This application is frozen
executable = /home/gelonida/so/pyinst/dist/minitst File = minitst.py mydir = /home/gelonida/so/pyinst
MEIPASS /tmp/_MEIKGqah9
will open /tmp/_MEIKGqah9/data/tst.txt
Hello
Now concerning your code.
I compacted the code to determine the datadir a little, but it is the same logic as in the upper example
import os, sys
from con import * # this is just a configuration file that has g='play' in it.
import subprocess
basedir = getattr(sys, "_MEIPASS", os.path.realpath(os.path.dirname(__file__)))
f=open('testfile1','w')
f.write('This has worked')
f.close()
file=os.path.join(basedir, 'data/bell.mp3')
if 'play' == g:
subprocess.call(['/usr/bin/cvlc',file])
I'm having an issue due to the fact that in my Python code os.system(filePath) will execute but the code stops until I manually close the window of the opened PDF file.
I would like to open a PDF file use openCV to capture my screen thus capturing the image of the file. This becomes an issue if the code does not run without me closing the window...
CODE:
import numpy as np
import shutil,os, cv2, SendKeys, win32com.client
#While our In File has stuff in it
while(os.listdir(pathForInFile)!=[]):
for subdir, dirs, inFile in os.walk(pathForInFile):
for fileName in inFile:
filePath= subdir+os.sep+fileName
os.system(filePath)
print "THIS WILL RUN NOT UNTIL I CLOSE FILE"
shell.SendKeys('{DOWN}')
You can use this solution both on Windows 8.1 (tested in a virtual machine):
import os
os.system('start path_to_my_filename.pdf')
print("You do not need to close the opened PDF file to run and see this")
and Ubuntu (14.04.4 LTS):
import os
# f = /home/begueradj/Desktop/metasploitBible.pdf'
os.system('xdg-open path_to_my_filename.pdf')
print("You do not need to close the opened PDF file to run and see this")
So I have Foo.app, which is configured to run Foo.app/Contents/MacOS/foo.py when it is launched. In the app's Info.plist file I also have it set as the application to handle the launching of ".bar" files. When I double-click a .bar file, Foo.app opens as expected.
The problem is that when a file is opened in this way, I can't figure out how to get the path to the opened file in my foo.py script. I assumed it would be in sys.argv[1], but it's not. Instead, sys.argv[1] contains a strange string like "-psn_0_2895682".
Does anyone know how I can get the absolute path to the opened file? I've also checked os.environ, but it's not there either.
You can get your app's process ID then ask the OS for all open files using lsof, looking for your process's ID:
from string import *
from os import getpid
from subprocess import check_output, STDOUT
pid = getpid()
lsof = (check_output(['/usr/sbin/lsof', '-p', str(pid)], stderr=STDOUT)).split("\n")
for line in lsof[1:]:
print line
The regular files will be of type 'REG' in the fifth column, [4] if you're indexing in.
Files open within the running code can be displayed in a similar way:
from string import *
from os import getpid
from subprocess import check_output, STDOUT
import re
pid = getpid()
f = open('./trashme.txt', 'w')
f.write('This is a test\n')
lsof = (check_output(['/usr/sbin/lsof', '-p', str(pid)], stderr=STDOUT)).split("\n")
print lsof[0]
for line in lsof[1:]:
if (re.search('trashme', line)): print line
f.close
Which results in:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python 6995 greg 3w REG 14,2 0 2273252 /Users/greg/Desktop/trashme.txt