when I try to run these two scripts together after a few tries it stops working? Is this because of the import module?
test1.py
test = input("Go to new script?: ")
if test=="yes":
print("going to new script")
import test2
test2.py
test = input("Go to old script?: ")
if test=="yes":
print("going to new script")
import test1
Error is that it ends itself.
C:\Users\bj\Desktop>python test1.py
Go to new script?: yes
going to new script
Go to old script?: yes
going to new script
Go to new script?: yes
going to new script
C:\Users\bj\Desktop>
import remember already imported files and it doesn't import them again.
Better put code in functions and import function from second file to first file and run it in loop . Second function should use return to go back to first function.
test2.py
def func2():
while True:
answer = input("Go to old script?: ")
if answer.lower() == "y":
print("Going back to old script")
return
test1.py
from test2 import func2
def func1():
while True:
answer = input("Go to new script?: ")
if answer.lower() == "y":
print("Going to new script")
func2()
func1()
Related
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.
I'm creating a virtual OS with different files, like boot.py and Run.py
It worked for a while until I typed this in:
if Run.run == 0:
error()
else:
start()
There is no errors saying about it like red lines or any. Now I get this error:
AttributeError("module 'boot' has no attribute 'bootup'",)
Here's the code:
boot.py:
#Imports
import Run
#Varibles
name = "PyOS"
version = 1
creator = "© Dragon Softwares"
def bootup(run):
if Run.run == 0:
error()
else:
start()
def start():
print("Starting PyOS")
print("Version ", version)
def error():
print("Please Run 'Run.py' To bootup the system")
bootup()
Run.py:
#Imports
import time
import boot
#Varibles
run = 0
def main():
run = 1
time.sleep(0.1)
boot.bootup
main()
You have a circular import. Don't have boot import Run and vice-versa.
What happens now is:
Run.py is executed as the __main__ module.
The line import boot is reached and executed.
boot has not been imported before, so boot.py is found and loaded to be the boot module.
The line import Run is reached and executed.
Run has not been imported before, so Run.py is found and loaded to be the Run module. Note: that Run.py is also used for __main__ does not matter here.
The line import boot is reached and executed.
boot is already being imported, so it used to set the name boot in the Run module
Various other names are set in the Run module namespace (run and main).
The line main() is reached and executed
The main() function references boot.bootup, which doesn't exist yet, because the boot module top-level code never reached the def bootup(run): line.
Instead of importing Run, pass the run value as a parameter to the boot function:
def main():
run = 1
time.sleep(0.1)
boot.bootup(run)
Also, don't call bootup() at the end of the boot module. That function call will be executed when you import boot, and makes no sense there. If you want to present an error message, use a if __name__ == '__main__': guard:
if __name__ == '__main__':
import sys
error()
sys.exit(1)
The if test will only ever be true if you ran boot.py as the script.
I tried to make it only ask "do you want to continue" 3 times but it doesn't seem to work, it just kept on running. How do I fix this? It is a chat-response program which the computer askes one question and the user response.
def choice():
prompts = [feeling, homesick, miss]
random.choice(prompts)()
for item in range(3):
choice()
This is the code I have written for it. but it does not work.
import random
name = input("What is your name? ")
def restart():
restart=input('do you want to continue? ')
if restart=='yes':
choice()
else:
print("ok, see you later!")
exit()
def feeling():
response = input("How are you feeling right now {name}?".format(name=name))
if response == "tired":
tired = ['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
print(random.choice(tired))
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def homesick():
response = input("Do you miss your home? ")
if response == "yes":
yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
print(random.choice(yes))
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def miss():
response = input("Who do you miss?")
if response == "my mom":
print("Mom will be in town soon")
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def choice():
prompts = [feeling, homesick, miss]
random.choice(prompts)()
for item in range(3):
choice()
The comment from darvark is correct. If you want to keep the rest of your code the same, then I would just modify the restart function to look something like this:
import sys
def restart():
if input('do you want to continue? ') != 'yes':
sys.exit()
This way, if the user responds with anything other than 'yes', the program will quit; however, if they respond with 'yes', then the call to restart will simply do nothing, and your loop should advance to the next iteration.
One more note: It is not recommended to call the exit function within a program, since it is just a helper function to be used when you're running the Python interpreter. Within a program, you should import the sys module and call sys.exit. Source: Difference between exit() and sys.exit() in Python
I made a program that asks you at the end for a restart.
I import os and used os.execl(sys.executable, sys.executable, * sys.argv)
but nothing happened, why?
Here's the code:
restart = input("\nDo you want to restart the program? [y/n] > ")
if str(restart) == str("y"):
os.execl(sys.executable, sys.executable, * sys.argv) # Nothing hapens
else:
print("\nThe program will be closed...")
sys.exit(0)
import os
import sys
restart = input("\nDo you want to restart the program? [y/n] > ")
if restart == "y":
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
else:
print("\nThe program will be closed...")
sys.exit(0)
os.execl(path, arg0, arg1, ...)
sys.executable: python executeable
os.path.abspath(__file__): the python code file you are running.
*sys.argv: remaining argument
It will execute the program again like python XX.py arg1 arg2.
Maybe os.execv will work but why not use directly using os.system('python "filename.py"') if you have environment and path variable set something like :
import os
print("Hello World!")
result=input("\nDo you want to restart the program? [y/n] > ")
if result=='y':
os.system('python "C:/Users/Desktop/PYTHON BEST/Hackerrank.py"')
else:
print("\nThe program will be closed...")
try using;
while True:
answer = input("\nDo you want to restart the program? [y/n] > ")
if answer == "n":
print("\nOk, Bye!")
break
or
retry = True
while retry:
answer = input("\nDo you want to restart the program? [y/n] > ")
if answer == "n":
print("\nOk, Bye!")
retry = False
It is a way that you can easily modify to your liking, and it also means that you can load variables once instead of loading them every time you restart. This is just a way to do it without any libraries. You indent all your code and put it in a while loop, and that while loop determines whether your code restarts or not. To exit it, you put in a break or change a variable. It is easiest because you don't have to understand a new library.
Just import the program you want to restart and run it under the desired condition like this
Title: hello. py
import hello
if (enter generic condition here):
hello
os.execv(sys.executable, ['python'] + sys.argv)
solved the problem.
This question already has answers here:
What is the best way to call a script from another script? [closed]
(16 answers)
Closed 6 years ago.
I have tried every thing from
if __name__ == "__main__":
to
os.system()
I have looked through all the other similar questions on here and read official Python documentation.
I can't get this
import os
ask1 = raw_input("Create bid? ")
create = "createbid.py %s" % ()
def questions():
if ask1 == "yes":
os.system(create)
if ask1 == "no":
quit()
question()
to run the ceatebid.py file reliably. I got it to work with
if __name__ == "__main__":
but what if I also want to call another script?
I want to call different scripts based on how the questions are answered.
I'm not sure exactly what you're trying to do, but in general you should be able to do something like this.
import foo
import bar
ask = raw_input("Do something?")
if ask.lower() in ('yes', 'y'):
foo.do_something()
else:
bar.do_other()
The key to using os.system("python createbid.py") is to pass in a shell command in string format.
If you want to communicate with that script you probably want subprocess.
See the answer from this question: running bash commands in python
This was probably answered here: What is the best way to call a Python script from another Python script?
So, you need to define some method in you createbid.py (and other scripts):
def run()
print 'running'
then in your main script,
import createbid
def questions():
if ask1 == "yes":
createbid.run()
if ask1 == "no":
quit()
if __name__ == '__main__':
questions()
Nowadays, the recommended way to launch other processes is to use the subprocess module.
It's relatively easy to do. Here's a simple way to apply it to your problem:
import subprocess
import sys
create = [sys.executable, 'createbid.py']
def question(ans):
if ans == 'yes':
subprocess.call(create)
elif ans == 'no':
quit()
ask1 = raw_input('Create bid? ')
question(ask1)
print('done')
Note: When createbid.py (or some other script) is executed this way,
__name__ == '__main__' will be True, unlike it would be if it had been imported.
Alternatively, you could use exec (statement in Python2, function in Python3).
Suppose your script scriptA is stored in a file named scriptA.py. Then:
scriptContent = open("scriptA.py", 'r').read()
exec(scriptContent)
The merit of this is that exec allows you to define variables before, and use them inside of the script.
So if you were to define some parameters before running the script, you could still call them in your solution:
#Main script
param1 = 12
param2 = 23
scriptContent = open("scriptA.py", 'r').read()
exec(scriptContent)
#scriptA.py
print(param1 + param2)
Still, this approach is more like a fun trick, and depending on the situation, there should be several ways to do better.
Thanks for the help! I combined a few answers to get it working.
This works:
import seebid
import createbid
ask1 = raw_input("Create bid? ")
ask2 = raw_input("View bid? ")
create = createbid
see = seebid
def questions():
if ask1.lower() in ('yes', 'y'):
create.createbd()
elif ask1.lower() in ('no', 'n'):
ask2
if ask2.lower() in ('yes', 'y'):
see.seebd()
if __name__ == "__main__":
questions()