My app is in VB.Net. I have a textbox. The user writes a piece of Python code init. I want to run this code. For example, the code in textbox is something like this:
print 7*7
the result of running this code in Python is 49. But if the user forgets a space and writes:
print7*7
the result of running this code in Python is:
Traceback (most recent call last):
File "vm_main.py", line 33, in <module>
import main
File "/tmp/vmuser_jrlbqyaetu/main.py", line 8, in <module>
print7*7
NameError: name 'print7' is not defined
Now I want to save the result of running code (error or correct data) in a string in VB.Net. Questions:
What is the data type of the result of running the code?
Is it possible to access it?
Is it possible to save it? Is it possible to save it in a string? If yes, how?
You can try this:
import sys
f = open('output.txt', 'w')
sys.stdout = f
###############
#your code here
##############
And than all outputs will be written in ouput?txt
Related
I am taking cs50 class. Currently on Week 7.
Prior to this coding, python was working perfectly fine.
Now, I am using SQL command within python file on VS Code.
cs50 module is working fine through venv.
When I execute python file, I should be asked "Title: " so that I can type any titles to see the outcome.
I should be getting an output of the counter, which tracks the number of occurrence of the title from user input.
import csv
from cs50 import SQL
db = SQL("C:\\Users\\wf user\\Desktop\\CODING\\CS50\\shows.db")
title = input("Title: ").strip()
#uses SQL command to return the number of occurrence of the title the user typed.
rows = db.execute("SELECT COUNT(*) AS counter FROM shows WHERE title LIKE ?", title) #? is for title.
#db.execute always returns a list of rows even if it's just one row.
#setting row to the keyword which is is rows[0]. the actual value is in rows[1]
row = rows[0]
#passing the key called counter will print out the value that is in rows[1]
print(row["counter"])
I have shows.db in the path.
But the output is printing "Found". It's not even asking for a Title to input.
PS C:\Users\wf user\Desktop\CODING\CS50> python favoritesS.py
Found
I am expecting the program to ask me "Title: " for me, but instead it's print "Found"
In cs50, the professor encountered the same problem when he was coding phonebook.py, but the way he solved the problem was he put the python file into a separate folder called "tmp"
I tried the same way but then I was given a long error message
PS C:\Users\wf user\Desktop\CODING\CS50> cd tmp
PS C:\Users\wf user\Desktop\CODING\CS50\tmp> python favoritesS.py
Traceback (most recent call last):
File "C:\Users\wf user\Desktop\CODING\CS50\tmp\favoritesS.py", line 5, in <module>
db = SQL("C:\\Users\\wf user\\Desktop\\CODING\\CS50\\shows.db")
File "C:\Users\wf user\AppData\Local\Programs\Python\Python311\Lib\site-packages\cs50\sql.py", line 74, in __init__
self._engine = sqlalchemy.create_engine(url, **kwargs).execution_options(autocommit=False, isolation_level="AUTOCOMMIT")
File "<string>", line 2, in create_engine
File "C:\Users\wf user\AppData\Local\Programs\Python\Python311\Lib\site-packages\sqlalchemy\util\deprecations.py", line 309, in warned
return fn(*args, **kwargs)
File "C:\Users\wf user\AppData\Local\Programs\Python\Python311\Lib\site-packages\sqlalchemy\engine\create.py", line 518, in create_engine
u = _url.make_url(url)
File "C:\Users\wf user\AppData\Local\Programs\Python\Python311\Lib\site-packages\sqlalchemy\engine\url.py", line 732, in make_url
return _parse_url(name_or_url)
File "C:\Users\wf user\AppData\Local\Programs\Python\Python311\Lib\site-packages\sqlalchemy\engine\url.py", line 793, in _parse_url
raise exc.ArgumentError(
sqlalchemy.exc.ArgumentError: Could not parse SQLAlchemy URL from string 'C:\Users\wf user\Desktop\CODING\CS50\shows.db'
Here is the proof that the code I posted is the same code I am working on.
I use Start Debugging under Run menu on VSCode and it's working! But not when I don't use debugging.
Is this the library you are using? https://cs50.readthedocs.io/
It may be that one of your intermediate results is not doing what you think it is. I would recommend you put print() statements at every step of the way to see the values of the intermediate variables.
If you have learned how to use a debugger, that is even better.
I'm trying to run a sample function that allows a user to execute arbitrary code
Note: I"m assuming this is ok because Azure Functions will by default provide a sandbox. (And the end user will need to write code with dataframes, objects etc. I've looked into pypy.org but don't think I need it as I am not worried about attacks that use it as a spambot or something):
import os
import json
import ast
print('==============in python function========================')
postreqdata = json.loads(open(os.environ['req']).read())
response = open(os.environ['res'], 'w')
response.write("hello world from "+postreqdata['name'])
response.close()
logic = (postreqdata['logic'])
eval(logic)
but I keep getting the following output/error:
2018-01-17T09:09:08.949 ==============in python function========================
2018-01-17T09:09:09.207 Exception while executing function: Functions.ccfinopsRunModel. Microsoft.Azure.WebJobs.Script: Traceback (most recent call last):
File "D:\home\site\wwwroot\ccfinopsRunModel\run.py", line 12, in <module>
eval(logic)
File "<string>", line 1
print('code sent from client')
^
SyntaxError: invalid syntax
.
My POST request body contains the following:
{
"name": "Python Function App",
"logic": "print('code sent from client')"
}
So the "logic" variable is being read in, and eval() is trying to interpret the string as python code, but it is causing a Syntax Error where there appears to be none.
What am I doing wrong? If there was a restriction on 'eval' I'm assuming it would say that instead of "Syntax Error"
Thanks for any help you can provide!
Use exec to run your code. eval is used evaluating expressions.
logic = (postreqdata['logic'])
exec(logic)
Also can try sending your code as multi-line string as below,
>>> s = '''
for i in range(3):
print("i")
'''
>>> exec(s)
0
1
2
I write a program that can open a particular file, i.e., a Flash file, positioning it at particular position and closing it(not minimizing but exitting).
The first second target is ok by os.startfile('file.swf'), finding its hwnd by win32gui.FindWindow(None, file.swf) and positioning it by win32gui.MoveWindow(hwnd,0,0,800,600,True), however, the win32gui.DestroyWindow(hwnd) can't work and I don't know why.
Here is the error message below:
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
win32gui.DestroyWindow(hwnd1)
error: (5, 'DestroyWindow', '\xa6s\xa8\xfa\xb3Q\xa9\xda\xa1C')
What is wrong with it? How to fix it?
edit:
my code is:
import win32gui
import os
"""
monitoring a folder which will be updated per one miniute
if the temperature changed the program will open a particular file to display
"""
FLASH_PATH="santa"
PIC_PATH=""
TEMP_PATH="Temperatures/"
file_name="led_20.swf"
filePath=os.path.join(FLASH_PATH,file_name)
os.startfile(filePath)
hwnd=win32gui.FindWindow(None,file_name)
win32gui.MoveWindow(hwnd,0,0,800,600,True)
"""
display it for a few minute and close it
"""
Error 5 is ERROR_ACCESS_DENIED. DestroyWindow() can only be called by the thread that created the window. Post or send a WM_DESTROY message instead.
Q. Write a search engine that will take a file (like an html source page) and extract all of the email addresses. It will then print them out in an ordered list. The file may contain a lot of messy text (i.e. asda#home is not valid.. and there can be a lot of #'s in the file in roles other than emails!)
For testing purposes, this is the text file I have been using:
askdalsd
asd
sad
asd
asd
asd
ad
asd
asda
da
moi1990#gmail.com
masda#sadas
223#home.ca
125512#12451.cpm
domain#name.com
asda
sda
as
da
ketchup#ketchup##%##.com
onez!es#gomail.com
asdasda#####email.com
asda#asdasdaad.ca
moee#gmail.com
And this is what I have so far:
import os
import re
import sys
def grab_email(file):
email_pattern = re.compile(r'\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b',re.IGNORECASE)
found = set()
if os.path.isfile(file):
for line in open(file, 'r'):
found.update(email_pattern.findall(line))
for email_address in found:
print (email_address)
if __name__ == '__main__':
grab_email(sys.argv[1])
grab_email('email_addresses.txt')
Now the problem I am having is that after a certain point, the program crashes. This is the output:
125512#12451.cpm
es#gomail.com
asda#asdasdaad.ca
223#home.ca
moee#gmail.com
moi1990#gmail.com
domain#name.com
Traceback (most recent call last):
File "D:/Sheridan/Part Time/TELE26529 Linux Architecture w. Network Scripting/Python Assignment 3.5/question1.py", line 17, in <module>
grab_email('email_addresses.txt')
File "D:/Sheridan/Part Time/TELE26529 Linux Architecture w. Network Scripting/Python Assignment 3.5/question1.py", line 14, in grab_email
grab_email(sys.argv[1])
IndexError: list index out of range
What am I doing wrong here and how do I fix this? How can I more effectively handle these exceptions?
The problem is this part:
if __name__ == '__main__':
grab_email(sys.argv[1])
Your program is crashing because it is processing this inside of the grab_email function. Since you are running from the interpreter, the if statement will of course evaluate to True. Then, since you have passed no command line arguments, you are attempting a non-existing list element, causing the error you get.
To fix, just dedent! It should look like:
import os
import re
import sys
def grab_email(file):
email_pattern = re.compile(r'\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b',re.IGNORECASE)
found = set()
if os.path.isfile(file):
for line in open(file, 'r'):
found.update(email_pattern.findall(line))
for email_address in found:
print (email_address)
if __name__ == '__main__':
grab_email(sys.argv[1])
This will now run correctly from the command line (assuming you pass the file name correctly from the command line). I have also removed the extraneous function call.
Of course, if you just want this to run in the interpreter, take out the if statement and reinstate the function call I removed. You could also do this:
if __name__ == '__main__':
if len(sys.argv)>1:
grab_email(sys.argv[1])
else:
grab_email('email_addresses.txt')
Which isn't great, per se, but handles that particular error (while introducing another potential one).
I am writing a Python script to notify me when changes are made to a webpage and store the current state of the page to a file in order to resume seamlessly after rebooting.
The code is as follows:
import urllib
url="http://example.com"
filepath="/path/to/file.txt"
try:
html=open(filepath,"r").read() # Restores imported code from previous session
except:
html="" # Blanks variable on first run of the script
while True:
imported=urllib.urlopen(url)
if imported!=html:
# Alert me
html=imported
open(filepath,"w").write(html)
# Time delay before next iteration
Running the script returns:
Traceback (most recent call last):
File "April_Fools.py", line 20, in <module>
open(filepath,"w").write(html)
TypeError: expected a character buffer object
------------------
(program exited with code: 1)
Press return to continue
I've no idea what this means. I'm relatively new to Python. Any help would be much appreciated.
urllib.urlopen does not return a string, it returns a response as a file-like object. You need to read that response:
html = imported.read()
Only then is html a string you can write to a file.
As an aside, using open(filename).read() is not considered good style, because you never close the file. The same goes for writing. Try using a context manager instead:
try:
with open(filepath,"r") as htmlfile:
html = htmlfile.read()
except:
html=""
The with block will automatically close the file when you leave the block.