I am trying to make a simple AFK script for if I need to leave my pc for short period and the code works on it's own but when I try to use one script to run another, It runs but then stops a few seconds later with exit code 0. I'm not sure what's wrong and I've tried multiple things such as:
import test1
test1.run()
And that doesn't seem to work. Every site I find tells me to use the above example or stuff such as exec which I've been told is dangerous. Note: a text file named 'bridge' will have to be created so the file can be stopped
main.py
import os
from output import run
import keyboard
from time import sleep
print('Start afk program? (Y/N)')
cmd = str.lower(input('> '))
if cmd == 'y':
print('Use X to Stop')
print('Starting in 10 seconds...')
run()
while True:
if keyboard.is_pressed('x'):
print('exit key pressed')
x = '1'
else:
x = '0'
if os.path.exists('bridge.txt'):
with open('bridge.txt', 'w') as file:
file.write(x)
file.write('\n')
file.close()
else:
exit('file not found')
if x == '1':
exit(0)
sleep(0.1)
output.py
import os
from time import sleep
from pynput.keyboard import Controller
keyboard = Controller()
def run():
global keyboard
sleep(10)
keyboard = Controller()
count = 0
while True:
if os.path.exists('bridge.txt'):
with open('bridge.txt', 'r') as file:
content = file.readlines()
for line in content:
if line[0] == '1':
exit(0)
if count == 1:
press_key('w')
elif count == 2:
press_key('a')
elif count == 3:
press_key('s')
elif count == 4:
press_key('d')
elif count == 10:
count = 0
press_key('q')
count += 1
sleep(0.1)
def press_key(key):
keyboard.press(key)
sleep(0.5)
keyboard.release(key)
run()
I get that having the two systems apart can be easily avoided and will be fixed later, but the answer to this question will help me with other projects
For me (Python 3.8), your code works fine if you simply type on the terminal
python main.py
provided that you comment out or delete the last line in output.py:
# run()
which would execute function run upon importing output in main. The program also works if I import from a local module
import output
output.run()
If for some reason you're trying to import output from a different directory, you may have to deal with relative imports -- a subject nothing to do with the specific implementation of your scripts.
This code seems to have couple of problems from initial check.
Since you are calling run() before the if keyboard.is_pressed('x'):, it will always run in infinite loop.
Also, if line[0] == '1':, this needs to be changed to if line[-1] == '1': to check the last character entered, but since the code never reached the line to take x as input, entering a value x will not work either.
There are logical errors here.
Related
I want to make a system in python what was listen to keypresses and when I hit enter something happens depends on the value of the command I write.
How can I do this?
I try to write this:
import keyboard
def run_buffer(cmd):
print("\nThe buffer value is: {}, The buffer size is: {}".format(cmd, len(cmd)), end="")
buffer = ""
def on_press(e):
global buffer
if e.name == "enter": # When I hit enter I need to run the 'command' and emtpy the buffer.
run_buffer(buffer)
buffer = ""
elif e.name == "backspace":
buffer = buffer[0:-1]
elif e.name == "f4":
print("Asd")
elif len(e.name) == 1:
buffer += e.name
keyboard.on_press(on_press)
while True: # This was just for the script has runtime and won't stop immediately.
a = 0
When I run the script sometimes works perfectly, but sometimes it's just too late and the cursor not follow my expectations.
I get this in the console
I hope someone can help me :D
Thanks for help, and sorry for my bad English.
I have a python script (xyz.py) that I run through the command prompt. My question is that don't we have any method which helps to resume the python code automatically from where it was lost the VPN connection, without any manual intervention. This will help to avoid monitoring the code frequently. Below is my code but it reads from the start if there is any disconnection. Please suggest.
filename = 'xyz.py'
while True:
p = subprocess.Popen('python '+filename, shell=True).wait()
""" #if your there is an error from running 'xyz.py',
the while loop will be repeated,
otherwise the program will break from the loop"""
if p != 0:
continue
else:
break
If me, time.sleep will be used:
import os
import time
from datetime import datetime
import requests
script = 'xyz.py'
def main():
network_check_url = 'http://8.8.8.8'
while True:
try:
requests.get(network_check_url)
except Exception as e:
print(datetime.now(), e)
time.sleep(1)
else:
print('Network is ok. {datetime.now():%Y-%m-%d_%H:%M:%S}')
os.system(f'python {script}')
return
if __name__ == '__main__':
main()
I have a [large] program which has suddenly started having an issue somewhere in an infinite loop. I cannot find this loop.
I did:
import pdb
pdb.run ( 'main()' )
So when the program enters the infinite loop, I hit control-C and...... it doesn't do anything. In fact, when I don't use pdb, control-C doesn't work either.
I'm not overriding the signals. Even if I do, control-C does nothing.
I ran this in lldb to see if the problem was somewhere in C++-land, and it's not - it's definitely frozen executing python crap (on thread #7 if that matters).
How do I get pdb to actually break on control-c?
Here's a simple 'debugger' that counts the number of times each line is passed over and raises an error when a line is hit too many times. Hopefully it can help find the loop if there really is one.
from bdb import Bdb
from collections import Counter
class LoopDetector(Bdb):
def __init__(self, maxhits):
Bdb.__init__(self)
self.counter = Counter()
self.maxhits = maxhits
def do_clear(self, arg):
pass
def user_line(self, frame):
filename = frame.f_code.co_filename
lineno = frame.f_lineno
key = (filename, lineno)
self.counter[key] += 1
if self.counter[key] >= self.maxhits:
raise ValueError('Too many hits at %s:%s' % key)
LoopDetector(1000).set_trace()
x = 1
y = x + 2
for i in range(200):
y += i
while True: # An exception gets raised here
y -= 1
print 'Does not get here'
This has to be done once per thread since it only affects the current thread.
Take a look in the PDB docs
You should add a breakpoint in you function (main in your example) using pdb.set_trace()
Then you can run the function using the command line (e.g python myprog.py) and the program will stop where you set the breakpoint.
import pdb
def main():
i = 0
while i<10:
print i
if i == 8:
pdb.set_trace()
i += 1
In the example above the the program will stop for debugging when i==8
I'm testing to see if the atexit module runs properly by attempting to print to file. The actual purpose of atexit will be to close the open port, however this is to test if atexit is working in the first place. However, atexit is not printing to file, any ideas why not? Any help is appreciated.
import atexit
import scala5
from scala5 import sharedvars
scalavars = sharedvars()
import serial
myPort=serial.Serial()
myPort.baudrate = 9600
myPort.port = "COM4"
myPort.parity=serial.PARITY_NONE
myPort.stopbits=serial.STOPBITS_ONE
myPort.bytesize=serial.EIGHTBITS
myPort.timeout=2
myPort.writeTimeout=2
try:
myPort.close()
except:
print("didn't need to close")
def port_exit():
fo = open("test.txt", "w")
fo.write("This works!")
fo.close()
myPort.open()
while True:
x = myPort.readline()
if x == "1\r\n":
scalavars.door = x
scala5.ScalaPlayer.Sleep(10)
atexit.register(port_exit)
port_exit()
You are registering the function after your while loop, which I am assuming you are exiting by killing the script (meaning the function port_exit isn't registered). If you register the function before the while then it should trigger and write the file when the script exits.
atexit.register(port_exit)
while True:
x = myPort.readline()
if x == "1\r\n":
scalavars.door = x
scala5.ScalaPlayer.Sleep(10)
I'm wondering how I would go about having a function refresh itself every minute, and check if a certain file it open. I don't exactly know how to go about this, but heres an example of what I'm looking for:
def timedcheck():
if thisgame.exe is open:
print("The Program is Open!")
else:
print("The Program is closed!")
*waits 1 minute*
timedcheck()
I would also like the script to refresh the function "def timedcheck():" every minute, so it keeps checking if thisgame.exe is open.
I searched through the site already, all suggestions recommended using "import win32ui", which gives me an error when I do.
To repeat this check every minute:
def timedcheck():
while True:
if is_open("thisgame.exe"):
print("The Program is Open!")
else:
print("The Program is closed!")
sleep(60)
Since it's a .exe file, I assume that by "check if this file is open" you mean "check if thisgame.exe" is running. psutil should be helpful - I haven't tested the below code, so it may need some tweaking, but shows the general principle.
def is_open(proc_name):
import psutil
for process in psutil.process_iter():
if proc_name in process.name:
return True
return False
You can use sleep from the time module with an input of 60 for 1 minute delay between checks. You can open the file temporarily and close it if not needed. An IOError will occur if the file is already opened. Catch the error with an exception and the program will wait for another minute before trying again.
import time
def timedcheck():
try:
f = open('thisgame.exe')
f.close()
print("The Program is Closed!")
except IOError:
print("The Program is Already Open!")
time.sleep(60) #*program waits 1 minute*
timedcheck()
Here's a variation on #rkd91's answer:
import time
thisgame_isrunning = make_is_running("thisgame.exe")
def check():
if thisgame_isrunning():
print("The Program is Open!")
else:
print("The Program is closed!")
while True:
check() # ignore time it takes to run the check itself
time.sleep(60) # may wake up sooner/later than in a minute
where make_is_running():
import psutil # 3rd party module that needs to be installed
def make_is_running(program):
p = [None] # cache running process
def is_running():
if p[0] is None or not p[0].is_running():
# find program in the process list
p[0] = next((p for p in psutil.process_iter()
if p.name == program), None)
return p[0] is not None
return is_running
To install psutil on Windows for Python 2.7, you could run psutil-0.6.1.win32-py2.7.exe.