Python string instead of unknown module name - python

Elham Here, I have made a simple code to something like this:
It accepts a string (name) from user
then it do some customization to the string (turn lowercase and replacing space with "_"{under score})
then after customization, it will search for a file with same name as string
then display the content of file. here is its code:
import coder
import time
import calc
mainfunc = ["clears", "action mode"]
main_loop = "main"
coder.clear_screen()
while main_loop == "main":
ask = input("BOT: You say? > ")
mask = ask.replace(" ", "_")
if mask == mainfunc[0]:
print("\n" * 100)
coder.clear_screen()
else:
prt = open(mask, "r")
pr = prt.read()
print(pr)
prt = open(mask, "r")
pr = prt.read()
print(pr)
this is what I can with text, and I have plan to do same thing with some python modules (like instead of displaying its code, it should execute the code), which search for the module name with the string given by user! its like unknown module to be executed with name of string.
I have tried getattr and others like {}.format, ...
but non worked. I have researched the documentation section of functions and modules, but didn't found anything to help or it was too confusing while I don't know name of what I am searching for : (
so if you know the fix, please send the code! You will save my life (I have made a bet with a friend on this :p
-thanks

Python's exec function will execute a string as raw code, which lets you do something like this:
module = input("Enter module to import:")
exec("import " + module)

Related

Why is this Python attribute error happening in my code?

This is my Python file (myfile.py). I am new to Python and programming.
title = "The meaning of life" #myfile.py
And it's present in 'learning_python' directory.
Try this:
from myfile import *
you should then be able to access the variable by it's name. (in your case, title)

Python's subprocess.check_output( )

I'm working with python's subprocess.check_output() and I'm using it to run a python file that takes certain attributes (like fileName, title, etc..). Everything works fine however, I decided to pass in a string variable instead of an actual string. This doesn't work and I'm not sure why. Does anyone see something that I don't?
import textFile
import upload
import subprocess
def upload(fileName):
arr = []
bunny = "big_buck_bunny.flv" #this is the variable
arr = textFile.readLine(fileName)
size = textFile.getLines(fileName)
i = 0
while(i < size):
f = open("upload.py-oauth2.json", 'w').close()
textFile.append("C:\\Users\\user1\\Desktop\\tester\\upload.py-oauth2.json",arr[i])
#This below is where i would like to pass in a variable
subprocess.check_output('python upload.py --file="C:\\Users\\...\\anniebot\\' + bunny)
i+=1
upload("C:\\Users\\user1\\Desktop\\tester\\accountList.txt")
So I pretty much would like to change the path constantly. The problem is, I cant figure out a way to get subprocess to work without passing in a fixed string.
i would like to do something like:-
subprocess.check_output('python upload.py --file="C:\\Users\\user1\\Videos\\anniebot\\" + bunny --title="title" --description="testing" --keywords="test" --category="22" --privacyStatus="public"')
Do you mean:
subprocess.check_output('python upload.py --file="C:\\Users\\...\\anniebot\\' + bunny + '" --title= ...')
So basically concatenate the string using the single quote instead of the double quote you are using.

How to read next logical line in python

I would like to read the next logical line from a file into python, where logical means "according to the syntax of python".
I have written a small command which reads a set of statements from a file, and then prints out what you would get if you typed the statements into a python shell, complete with prompts and return values. Simple enough -- read each line, then eval. Which works just fine, until you hit a multi-line string.
I'm trying to avoid doing my own lexical analysis.
As a simple example, say I have a file containing
2 + 2
I want to print
>>> 2 + 2
4
and if I have a file with
"""Hello
World"""
I want to print
>>>> """Hello
...World"""
'Hello\nWorld'
The first of these is trivial -- read a line, eval, print. But then I need special support for comment lines. And now triple quotes. And so on.
You may want to take a look at the InteractiveInterpreter class from the code module .
The runsource() method shows how to deal with incomplete input.
Okay, so resi had the correct idea. Here is my trivial code which does the job.
#!/usr/bin/python
import sys
import code
class Shell(code.InteractiveConsole):
def write(data):
print(data)
cons = Shell()
file_contents = sys.stdin
prompt = ">>> "
for line in file_contents:
print prompt + line,
if cons.push(line.strip()):
prompt = "... "
else:
prompt = ">>> "

Trouble with Python: Opening an app/saving a file

I am a bit new to coding, I am trying to improve my skills. My preferred programming language is python. But I do need help with this bit of code. I am making an app called User Helper for my own use. I know that the code may look a bit sloppy, but when I posted it in for some reason I put four spaces in but it didn't turn to a block of code, so I had to manually put in the spaces.
But back to the topic at hand, my code has 2 problems (though you could probably find more.) I am not able to save my favorites to a document for later use when I open the app again. As well I don't know the code to open an app from python code.
I have tried many different methods including using the os function. I think I may need some sort of directory, but I'm sorry to say I am unfamiliar with directories and I have had trouble with them. The time function will be used later in the project. And for some reason when I run this program, it tries to find a path from the folder all my coding projects are in.
I also want to thank you for reading this, and I hope I can get this solved soon. I plan to become an active member in this community, and I can't wait to continue improving my skills in coding.
Thank you for your time!
import os
import time
def name():
print ""
print ""
print "Welcome to User Helper!"
name1 = raw_input("What is your name? ")
print ""
print "Welcom to User helper "+name1+"!"
def favorites():
print ""
print "Now opening Favorites settings..."
fav1 = raw_input("Favorite 1: ")
fav2 = raw_input("Favorite 2: ")
fav3 = raw_input("Favorite 3: ")
fav1full = fav1+".app"
fav2full = fav2+".app"
fav3full = fav3+".app"
fav1_path = os.path.abspath(fav1full)
fav2_path = os.path.abspath(fav2full)
fav3_path = os.path.abspath(fav3full)
os.system(fav1_path)
name()
favorites()
You can use os.chdir() to change default directory and os.startfile() to open the program or file directly. As for saving it for later use, if you want to save it to a text file, I'll include it in my answer.

Newbie question about file formatting in Python

I'm writing a simple program in Python 2.7 using pycURL library to submit file contents to pastebin.
Here's the code of the program:
#!/usr/bin/env python2
import pycurl, os
def send(file):
print "Sending file to pastebin...."
curl = pycurl.Curl()
curl.setopt(pycurl.URL, "http://pastebin.com/api_public.php")
curl.setopt(pycurl.POST, True)
curl.setopt(pycurl.POSTFIELDS, "paste_code=%s" % file)
curl.setopt(pycurl.NOPROGRESS, True)
curl.perform()
def main():
content = raw_input("Provide the FULL path to the file: ")
open = file(content, 'r')
send(open.readlines())
return 0
main()
The output pastebin looks like standard Python list: ['string\n', 'line of text\n', ...] etc.
Is there any way I could format it so it looks better and it's actually human-readable? Also, I would be very happy if someone could tell me how to use multiple data inputs in POSTFIELDS. Pastebin API uses paste_code as its main data input, but it can use optional things like paste_name that sets the name of the upload or paste_private that sets it private.
First, use .read() as virhilo said.
The other step is to use urllib.urlencode() to get a string:
curl.setopt(pycurl.POSTFIELDS, urllib.urlencode({"paste_code": file}))
This will also allow you to post more fields:
curl.setopt(pycurl.POSTFIELDS, urllib.urlencode({"paste_code": file, "paste_name": name}))
import pycurl, os
def send(file_contents, name):
print "Sending file to pastebin...."
curl = pycurl.Curl()
curl.setopt(pycurl.URL, "http://pastebin.com/api_public.php")
curl.setopt(pycurl.POST, True)
curl.setopt(pycurl.POSTFIELDS, "paste_code=%s&paste_name=%s" \
% (file_contents, name))
curl.setopt(pycurl.NOPROGRESS, True)
curl.perform()
if __name__ == "__main__":
content = raw_input("Provide the FULL path to the file: ")
with open(content, 'r') as f:
send(f.read(), "yournamehere")
print
When reading files, use the with statement (this makes sure your file gets closed properly if something goes wrong).
There's no need to be having a main function and then calling it. Use the if __name__ == "__main__" construct to have your script run automagically when called (unless when importing this as a module).
For posting multiple values, you can manually build the url: just seperate different key, value pairs with an ampersand (&). Like this: key1=value1&key2=value2. Or you can build one with urllib.urlencode (as others suggested).
EDIT: using urllib.urlencode on strings which are to be posted makes sure content is encoded properly when your source string contains some funny / reserved / unusual characters.
use .read() instead of .readlines()
The POSTFIELDS should be sended the same way as you send Query String arguments. So, in the first place, it's necessary to encode the string that you're sending to paste_code, and then, using & you could add more POST arguments.
Example:
paste_code=hello%20world&paste_name=test
Good luck!

Categories