How to run a seperate python program within a python program? - python

I am trying to implement a program that is executing another program over and over until the second program returns a proper output.
But the first program must not be halted after an error that occurred in the second program. I tried something like this, but the exec() function is not what I am looking for.
input_file = 'report.txt'
source_code = 'insert_prices.py'
correct_flag = 26
current_flag = 0
while(1):
with open(input_file, 'r') as file:
current_flag = int(file. readline().split(None, 1)[0])
if(current_flag == correct_flag):
break
else:
exec(open(source_code, encoding='utf-8').read())

Related

How to quit script when Telebot sees a new message

I have two python scripts which I run using a batch script. Once one script is executed, the next script starts. I need one of the scripts, the Telebot script, to quit after recording a message in a .json file. Unfortunately, while the message does get recorded, I am having trouble quitting the script, meaning my second python file is not being executed.
import telebot
import json
import os
import sys
import time
with open('JSON_file.json') as f:
data = json.load(f)
group_chat_id = 'CHAT_ID_HERE'
hbot = telebot.TeleBot('BOT_TOKEN_HERE')
hbot.send_photo(chat_id = group_chat_id, caption = data, photo = open('C:/Users/.../image.jpg', 'rb'))
temp = ""
#hbot.message_handler(func=lambda message: True)
def get_input(message):
global temp
message_str = str(message.text)
message_str = message_str.strip()
temp = message_str
print(temp)
with open('JSON_file.json', 'w') as json_file:
json.dump(temp, json_file)
hbot.stop_polling()
if temp != "":
quit()
return
if __name__ == "__main__":
hbot.polling()
I run the code(s) using an executable .bat file, however, the code below does not quit once a message is received. Does anyone know why the quit() command does not stop my code?
Thanks in advance)
I'd recommend using sys.exit instead of quit: https://docs.python.org/3/library/sys.html#sys.exit
In python, we have an in-built quit() function which is used to exit a python program. When it encounters the quit() function in the system, it terminates the execution of the program completely.
It should not be used in production code and this function should only be used in the interpreter.
Source: https://pythonguides.com/python-exit-command/

Why i cant come back to main input? (python3)

I'm building a terminal project. In my project, when user writes the command, i want to return to main input.
Codes:
write_Code = input(os.getcwd() + " > ")
# UCD "ls" Code
if write_Code == "ucd --ls":
print(os.listdir())
In this code i created a ls code. When user writes ucd --ls program is ending. But i want to back to main input. I tried while loop but it doesnt work. I research enough but i cant find what can i do
You can use a while loop to do this:
while True:
write_Code = input(os.getcwd() + " > ")
# UCD "ls" Code
if write_Code == "dir":
print(os.listdir())

Python file-reader will not run in IDLE but works fine in terminal?

So I created this lab assignment for class. It seemed fine, except for it doesn't run at all in idle. Idle opens, and then immediately closes. It ran fine in powershell, and the IDE i was using, but would not run at all for my professor.
The program just opens randomNumbers.txt and then lists the values inside. I have had no problems with any of my programs before this one, and this one seems to be the simplest. Is there a simple mistake I'm overlooking? As well as that, if you have any suggestions as to methods i can use to optimize this code id love the suggestions, I've been using python for 2 months now.
Sorry if this post was a bit long, just really confused.
import time, sys
def main():
global file
file = open("randomNumber.txt","r")
prepArray()
print("\n-----------\n# | Value\n-----------")
printArray()
file.close()
closeInput = input("\nPress ENTER to exit")
print("Closing...")
def prepArray():
global numberSplit
global file
openFile = input("Open randomNumber.txt (Y/N): ")
print("\n")
if openFile.lower() == "y":
try:
f = open("randomNumber.txt","r")
except IOError:
print("Error opening file: Did you run the generator first?")
main()
elif openFile.lower() == "n":
sys.exit()
else:
print("\nInvalid input, enter either (Y for yes, N for no)\n")
main()
numberSplit = file.readline()
numberSplit = numberSplit.split(",")
numberSplit = numberSplit[:-1]
def printArray():
global numberSplit
lineCount = 1
totalCount = 0
for item in numberSplit:
print(lineCount,"-",item)
lineCount += 1
totalCount += float(item)
print("\nTotal:",round((totalCount),2))
main()
randomNumbers.txt just contains
119.18,470.54,159.89,360.56,47.15,489.77,242.54,
I was testing your code and its work fine! I'm sure your problem is you haven't randomNumbers.txt in the same folder, please try to put your txt file in the same folder where is your script and it'll work! ;-)

Script writes in reverse

Sorry if I asked this wrong or formatted it wrong, this is my first time here.
Basically, this script is a very, very, simple text editor. The problem is, when it writes to a file, I want it to write:
Hi, my name
is bob.
But, it writes:
is bob.
Hi, my name
How can I fix this?
The code is here:
import time
import os
userdir = os.path.expanduser("~\\Desktop")
usrtxtdir = os.path.expanduser("~\\Desktop\\PythonEdit Output.txt")
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
def lowlevelinput():
cmd = input("\n$ ")
if(cmd == "/edit"):
editor()
elif(cmd == "/citenote"):
print("Well, also some help from internet tutorials.\nBut Brendan did all the scripting!")
lowlevelinput()
print("Welcome to the PythonEdit Basic Text Editor!\nDeveloped completley by Brendan*!")
print("Type \"/citenote\" to read the citenote on the word Brendan.\nType \"/edit\" to begin editing.")
lowlevelinput()
Nice puzzle. Why are the lines coming out in reverse? Because of output buffering:
When you write to a file, the system doesn't immediately commit your data to disk. This happens periodically (when the buffer is full), or when the file is closed. You never close f, so it is closed for you when f goes out of scope... which happens when the function editor() returns. But editor() calls itself recursively! So the first call to editor() is the last one to exit, and its output is the last to be committed to disk. Neat, eh?
To fix the problem, it is enough to close f as soon as you are done writing:
f = open(usrtxtdir,"a")
f.write(words + '\n')
f.close() # don't forget the parentheses
Or the equivalent:
with open(usrtxtdir, "a") as f:
f.write(words + '\n')
But it's better to fix the organization of your program:
Use a loop to run editor(), not recursive calls.
An editor should be writing out the file at the end of the session, not with every line input. Consider collecting the user input in a list of lines, and writing everything out in one go at the end.
If you do want to write as you go, you should open the file only once, write repeatedly, then close it when done.
You need to close your file after writing, before you try to open it again. Otherwise your writes will not be finalized until the program is closed.
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
f.close() # your missing line!
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
If you replace:
f = open(usrtxtdir,"a")
f.write(words + '\n')
with:
with open(usrtxtdir,"a") as f:
f.write(words + '\n')
It comes out in order. Pretty much always use with open() for file access. It handles the closing of the files for you automatically, even in the event of a crash. Although you might consider taking text in memory and writing it only upon quit. But that's not really part of the problem at hand.
Python's file.write() documentation states: "Due to buffering, the string may not actually show up in the file until the flush() or close() method is called"
Since you're recursively reopening the file and writing to it before closing it (or flushing the buffer), the outer value ('Hi, my name') isn't yet written when the inner frame (where you write 'is bob.') completes, which appears to automatically flush the write buffer.
You should be able to add file.flush() to correct it like this:
import time
import os
userdir = os.path.expanduser("~\\Desktop")
usrtxtdir = os.path.expanduser("~\\Desktop\\PythonEdit Output.txt")
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
f.flush() # <----- ADD THIS LINE HERE -----< #
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
def lowlevelinput():
cmd = input("\n$ ")
if(cmd == "/edit"):
editor()
elif(cmd == "/citenote"):
print("Well, also some help from internet tutorials.\nBut Brendan did all the scripting!")
lowlevelinput()
print("Welcome to the PythonEdit Basic Text Editor!\nDeveloped completley by Brendan*!")
print("Type \"/citenote\" to read the citenote on the word Brendan.\nType \"/edit\" to begin editing.")
lowlevelinput()
Also, don't forget to close your file after you're done with it!

How does a user input a filename?

I've written code for an assembler, but I am still new to python.
In my code I have the user input a file that will be converted into an assembly language. I think I've almost got it working, but I can't figure out where the user enters the file name.
I'm in (what I think is) IDLE, and then when I hit F5 it runs in the shell. I'm getting an error, but I'm pretty sure it's because no file name has been entered.
Where is the user supposed to input these kinds of things? Is this done from the python shell, or from the command line, do I need to turn it into an executable?
Can someone help clarify where the user is inputting all this information?
I'll put in a segment of code, although I don't think it's necessary to answer my questions, but maybe it'll give you a better idea of my issue.
if __name__ == '__main__':
import sys
if len(sys.argv) == 1:
print 'need filename'
sys.exit(-1)
table = SymbolTable()
parser = Parser(sys.argv[1])
parser.advance()
line = 0
while parser.hasMoreCommands():
if parser.commandType() == 'L_COMMAND':
table.addEntry(parser.symbol(), line)
else:
line += 1
parser.advance()
code = Code()
parser = Parser(sys.argv[1])
parser.advance()
var_stack = 16
while parser.hasMoreCommands():
cmd_type = parser.commandType()
if cmd_type == 'A_COMMAND':
number = 32768
try:
addr = int(parser.symbol())
except:
if table.contains(parser.symbol()):
addr = table.getAddress(parser.symbol())
else:
table.addEntry(parser.symbol(), var_stack)
addr = var_stack
var_stack += 1
bin_number = bin(number | addr)[3:]
assembly = '0' + bin_number
print assembly
elif cmd_type == 'C_COMMAND':
assembly = '111'
assembly += code.comp(parser.comp())
assembly += code.dest(parser.dest())
assembly += code.jump(parser.jump())
print assembly
parser.advance()
The part to note is at the beginning lines 4-6 where it's checking the file name. So once I run my program I get 'need filename' printed to the screen and an error message that looks like this:
Traceback (most recent call last):
File "C:\Python27\Assembler.py", line 98, in <module>
sys.exit(-1)
SystemExit: -1
So where can I input the filename to avoid this error?
The way you have it, Python expects the filename as an argument:
python file.py your_file.asm
If you want to prompt for a filename, use raw_input() (or input() for Python 3):
filename = raw_input('Enter a filename: ') or 'default_file.asm'
sys.argv contains command line arguments.
So, this script has to be run through command-line, for getting input, as said by blender, use raw_input (or input) for getting input from the user, if there are not enough command-line arguments.
Something like this:
if len(sys.argv) == 1:
print "You can also give filename as a command line argument"
filename = raw_input("Enter Filename: ")
else:
filename = sys.argv[1]
And change the line
parser = Parser(sys.argv[1])
To
parser = Parser(filename)

Categories

Resources