I'm creating a program in Python and I have a problem with a for loop and opening program in this loop.
The program is supposed to run e.g. 5 times and it only runs once
import subprocess
z = int(input())
def run():
subprocess.run('notepad.exe')
a = 0
while(a<z):
a = a + 1
run()
I've tried creating a function and replacing the for loop with a while loop but it doesn't work. Sorry for my English
Use subprocess.Popen('notepad.exe'), this will put the process in the background.
subprocess.run() will wait for the exit code I think, which waits until you close the notepad.
So full code is
import subprocess
z = int(input())
def run():
subprocess.Popen('notepad.exe')
a = 0
while(a<z):
a = a + 1
run()
You need to do pip install AppOpener first (or however you install modules for your device).
from AppOpener import open
z = int(input('Enter the number of times to open notepad: '))
def run():
open('notepad')
a = 0
while(a < z):
a = a + 1
run()
Additionally, for running any different apps, just change 'notepad' to the name of the app. (For Example: 'facebook')
Now it depends what you want. subprocess.run() opens the program, and pauses the code until you close notepad. Then, it will re open it, and do it z many times.
If you want to open z many instances of notepad at the same time you need to use `subprocess.Popen('notepad.exe', '-new-tab')
From the look of the code this may or may not be an issue. Python doesn't know where notepad.exe is located. You need to add the full path of the executable file. For example, try this:
import subprocess
z = int(input())
def run():
subprocess.run(r'C:\WINDOWS\system32\notepad.exe') #For most people this is the location of notepad.exe
a = 0
while(a<z):
a = a + 1
run()
Related
I've seen other questions posted along this line but I have a mainloop() function in my program which for most people seems to be the usual fix.
When attempting to launch the program from a command line prompt or terminal or just by double pressing to open it as a python shell on windows it briefly shows the command window and closes instantly. This happens on Windows 11 and Ubuntu. Unsure what is causing it see attached a photo of what is happening.
The CMD Prompt just flashes up and instantly closes with a similar occurrence on Ubuntu. There are print() functions in the script of which I see none running. I'd also like to mention that the program launches absolutely fine from Python IDLE - My personal choice of Python IDE.
I do have to add I have got a infinite loop of sorts running in my program code for which I will attach below. I've played around adding "root.update_idletasks()" and "root.update()" to the loop to no avail. I'm unsure of what other actions to take?
The Infinite Loop I have mentioned above is a defined function, being called with the "after" method "root.after(0,main_program_exec)" and then continuously run with another after method " root.after(500,main_program_exec)".
NOTE: Most of the code has been left out as this is an application I'll be using for work. - Sorry about messy code normally others don't have to read it! I also have included all modules imported in the case that one of those could be causing a issue!
CODE SNIPPIT:
from pymodbus.client import ModbusTcpClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from tkinter import *
import time
from PIL import ImageTk, Image
from tksheet import Sheet
def main_program_exec():
global client, datatype
root.update_idletasks()
root.update()
if program_mode.get():
pass
else:
a = RegType.returnSelection()
b = StartAdd_Entry_Widget.returnValue()
if b <=0:
b = 1
if b > 9999:
b = 9999
c = Length_Entry_Widget.returnValue()
if c >100:
c = 100
elif c < 1:
c = 1
try:
main_data = client.compile_data(a,c,b,datatype) #Mode, length, starting add, mode
update_table(main_data)
except Exception as e:
print(e)
pass
root.after(500, main_program_exec)
....
root.after(0, main_program_exec)
main loop()
As you see in the below code, it is possible to open a file in a directory and read it. now i want live_token read the file every 30 minutes and print it. Can anyone help me in this regard?
I found below code as scheduling to do a job but i don't know how to do needful modifications.
schedule.every(30).minutes.do()
Sorry if this question is so basic, I am so new with Python.
def read_key():
live_key_file_loc = r'C:\key.txt'
live_key_file = open(live_key_file_loc , 'r')
global key_token
time.sleep(6)
live_token=live_key_file.read()
print(live_token)
import time
sleep_time = 30 * 60 # Converting 30 minutes to seconds
def read_key():
live_key_file_loc = r'C:\key.txt'
live_key_file = open(live_key_file_loc, 'r')
global key_token
time.sleep(6)
live_token = live_key_file.read()
print(live_token)
while(True): # This loop runs forever! Feel free to add some conditions if you want!
# If you want to read first then wait for 30 minutes then use this-
read_key()
time.sleep(sleep_time)
# If you want to wait first then read use this-
time.sleep(sleep_time)
read_key()
#jonrsharpe is right. Refer to schedule usage. You should have a script which should keep running always to fetch the token every 30 minutes from the file. I have put below a script which should work for you. If you dont want to run this file in python always, look for implementing a scheduled job.
import schedule
import time
def read_key():
with open('C:\\key.txt' , 'r') as live_key_file_loc
live_token = live_key_file_loc.read()
print(live_token)
schedule.every(30).minutes.do(read_key)
while True:
schedule.run_pending()
time.sleep(1)
There are a few steps in this process.
Search for “Task Scheduler” and open Windows Task Scheduler GUI.
Go to Actions > Create Task…
Name your action.
Under the Actions tab, click New
Find your Python Path by entering where python in the command line. Copy the result and put it in the Program/Script input.
In the "Add arguments (optional)" box, put the name of your script. Ex. - in "C:\user\your_python_project_path\yourFile.py", put "yourFile.py".
In the "Start in (optional)" box, put the path to your script. Ex. - in "C:\user\your_python_project_path\yourFile.py", put "C:\user\your_python_project_path".
Click “OK”.
Go to “Triggers” > New and choose the repetition that you want.
For more details check this site -
https://www.jcchouinard.com/python-automation-using-task-scheduler/
I have decided for practice purposes, I'd write a Passwordgenerator and make it an executable.
My script is running as it is intended, and the compiling works as well, but when I run the exe file, nothing happens.
I run a Windows 10 system and use Python 3.6.x and I am not a beginner of python itself.
I looked up various pages on the internet, but I found nothing that helped me on that problem, my first problem was that the compiling didn't work but I already found that solution.
Edit: I tried to run the exe with the cmd and I get no output, instead I get a new line.
This is the setup code:
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"excludes": ["tkinter"]}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(name="Password",
version="1.0",
description="Generates a password made of 20 characters",
options={"build_exe": build_exe_options},
executables=[Executable("pass.py", base=base)])
And this is my program:
import random
import string
for i in range(20):
k = random.choice(string.ascii_letters)
j = random.randint(0, 9)
z = random.randint(1, 2)
if z == 1:
x = k
if z == 2:
x = j
print(x, end=" ")
I am grateful for any kind of insight.
Remove the two lines
if sys.platform == "win32":
base = "Win32GUI"
from your setup script and it should work.
base = "Win32GUI" tells cx_Freeze not to start a console window and should be used only if the main application starts a GUI (e.g. with PySide, PyQt, Tk, ...). It presumably also redirects the standard output away from the console if you run the executable from an already started console. In your case you have a console-based application and you thus want a console to be started and to receive the standard output. This behavior is partially explained in the cx_Freeze documentation.
Now if you run your executable without using the cmd (e.g. by double-clicking it in Windows-Explorer), it starts a console window, prints the output there, and closes the console immediately when the execution is finished. In your example script, you would like to have the time to read the output before the console closes, so what you need then is something to tell your script to wait before finishing, for example until you press a key. You can add
input("Press Enter to continue...")
at the end of your script for this purpose, see How do I make python to wait for a pressed key.
Add wait after the code so it doesn't finish immediately.
import random
import string
for i in range(20):
k = random.choice(string.ascii_letters)
j = random.randint(0, 9)
z = random.randint(1, 2)
if z == 1:
x = k
if z == 2:
x = j
print(x, end=" ")
import time
time.sleep(5) #<-- Sleep for 5 seconds
You can also use my Python Executable maker.
I have two user defined python scripts. First takes a file and processes it, while the second script takes the output of first and runs an executable, and supplies the output of first script to program with additional formatting.
I need to run these scripts via another python script, which is my main executable script.
I searched a bit about this topic and;
I can use importlib to gather the content of scripts so that I can call them at appropriate times. This requires the scripts to be under my directory/or modification to path environment variable. So it is a bit ugly looking at best, not seem pythonish.
Built-in eval function. This requires the user to write a server-client like structure, cause the second script might have to run the said program more than one time while the first script still gives output.
I think I'm designing something wrong, but I cannot come up with a better approach.
A more detailed explenation(maybe gibberish)
I need to benchmark some programs, while doing so I have a standard form of data, and this data needs to be supplied to benchmark programs. The scripts are (due to nature of benchmark) special to each program, and needs to be bundled with benchmark definition, yet I need to create this program as a standalone configurable tester. I think, I have designed something wrong, and would love to hear the design approaches.
PS: I do not want to limit the user, and this is the reason why I choose to run python scripts.
I created a few test scripts to make sure this works.
The first one (count_01.py) sleeps for 100 seconds, then counts from 0 to 99 and sends it to count_01.output.
The second one (count_02.py) reads the output of first one (count_01.output) and adds 1 to each number and writes that to count_02.output.
The third script (chaining_programs.py) runs the first one and waits for it to finish before calling the second one.
# count_01.py --------------------
from time import sleep
sleep(100)
filename = "count_01.output"
file_write = open(filename,"w")
for i in range(100):
#print " i = " + str(i)
output_string = str(i)
file_write.write(output_string)
file_write.write("\n")
file_write.close()
# ---------------------------------
# count_02.py --------------------
file_in = "count_01.output"
file_out = "count_02.output"
file_read = open(file_in,"r")
file_write = open(file_out,"w")
for i in range(100):
line_in = file_read.next()
line_out = str(int(line_in) + 1)
file_write.write(line_out)
file_write.write("\n")
file_read.close()
file_write.close()
# ---------------------------------
# chaining_programs.py -------------------------------------------------------
import subprocess
import sys
#-----------------------------------------------------------------------------
path_python = 'C:\Python27\python.exe' # 'C:\\Python27\\python.exe'
#
# single slashes did not work
#program_to_run = 'C:\Users\aaaaa\workspace\Rich_Project_044_New_Snippets\source\count.py'
program_to_run_01 = 'C:\\Users\\aaaaa\\workspace\\Rich_Project_044_New_Snippets\\source\\count_01.py'
program_to_run_02 = 'C:\\Users\\aaaaa\\workspace\\Rich_Project_044_New_Snippets\\source\\count_02.py'
#-----------------------------------------------------------------------------
# waits
sys.pid = subprocess.call([path_python, program_to_run_01])
# does not wait
sys.pid = subprocess.Popen([path_python, program_to_run_02])
#-----------------------------------------------------------------------------
My overall goal of the scripts is to do a efficient ping of a /8 network. To do this I am running 32 scripts at the same time to scan a /13 each.
the basic of the script is
import ipaddress
import time
import fileinput
import pingpack
set = 0
mainset =0
while mainset < 8:
while set < 256:
net_addr = ("10.{}.{}.0/24".format(mainset,set))
ip_net = ipaddress.ip_network(net_addr)
all_hosts = list(ip_net.hosts())
f_out_file=('{}_Ping.txt'.format(mainset))
for i in range(len(all_hosts)):
output = pingpack.ping("{}".format(all_hosts[i]))
if output != None:
with open(f_out_file,'a',newline="\n") as file:
file.write("{}, Y\r\n".format(all_hosts[i]))
print ("{}".format("Subnet Complete"))
set = set + 1
set=0
The script it self works and runs and gives me a good output when ran by it self. The issue i am running into is when i get 32 of these running for each subnet they run for about 8 set loops before the python process locks up and stops writing.
The script I am using to start the 32 is as follows
from subprocess import Popen, PIPE
import time
i = 0
count=0
while i < 32:
process = Popen(['ping{}.py'.format(i),"{}".format(count)], stdout=PIPE, stderr=PIPE, shell=True)
print(count)
print(i)
i = i + 1
count=count+8
time.sleep(1)
In this case; Yes; I do have 32 duplicate scrips each with a 2 lines changed for the different /13 subents. It may be as effect as some; but it gets them started and running.
How would I go about finding the reason for the stop for these scripts?
Side note: Yes I know I can do this with something like NMAP or Angry IP Scanner; but they both take 90+ hours to scan a entire /8; I am trying to shorten this down to something that can be ran in a more reasonable timeframe.
Your first problem is that set is never set back to zero when you move on to the next mainset. Your second problem is that mainset never increments. Rather than a pair of obscure while-loops, why not:
for mainset in xrange(8):
for set in xrange(256):
Also, in range(len(all_hosts)) is a code smell (and it turns out that you never use i except to write all_hosts[i]). Why not:
for host in all_hosts: