I have been trying to debug the below python cgi code but doesn't seems to work. When i try in new file it these three lines seems to work
filename=unique_file('C:/wamp/www/project/input.fasta')
prefix, suffix = os.path.splitext(filename)
fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname)
But, when i try like this way then i get error unique_file is not define >>>
form=cgi.FieldStorage()
i=(form["dfile"].value)
j=(form["sequence"].value)
if (i!="" and j=="" ):
filename=(form["dfile"].filename)
(name, ext) = os.path.splitext(filename)
alignfile=name + '.aln'
elif(j!="" and i==""):
filename=unique_file('C:/wamp/www/project/input.fasta')
prefix, suffix = os.path.splitext(filename)
fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname)
file = open(filename, 'w')
value=str(j)
file.write(value)
file.close()
(name, ext) = os.path.splitext(filename)
alignfile=name + '.aln'
What i am trying to do is check two options from form:- Fileupload and textarea. If fileupload is true then there is nothing to do except separating file and its extension. But when textarea is true then i have to generate unique file name and write content in it and pass filename and its extension.
Error i got is...
type 'exceptions.NameError'>: name 'unique_file' is not defined
args = ("name 'unique_file' is not defined",)
message = "name 'unique_file' is not defined"
Any suggestions and corrections are appreciated
Thanks for your concern
unique_file() isn't a built-in function of Python. So I assume, either you forget a line in your first code snippet which actually imports this function, or you configured your python interpreter to load a startup file (http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP). In the second case, the CGI script can't find this function because it runs with the web server identity which probably lacks the PYTHONSTARTUP env. variable definition.
You need to either import or define your unique_file method before using it.
They will look something like:
from mymodule import unique_file
or:
def unique_file():
# return a unique file
Usually when a compiler or interpreter says something isn't defined, that's precisely what the problem is. So, you have to answer the question "why is it not defined?". Have you actually defined a method named "unique_file"? If so, maybe the name is misspelled, or maybe it's not defined before this code is executed.
If the function is in another file or module, have you imported that module to gain access to the function?
When you say it works in one way but not the other, what's the difference? Does one method auto-import some functions that the other does not?
Since unique_file is not a built-in command, you're probably forgetting to actually define a function with that name, or forgetting to import it from an existing module.
Related
I'm learning Python as someone more familiar with databases and ETL. I'm not sure where target comes from in the following code.
from sys import argv
script, filename = argv
target = open(filename, 'w')
I think argv is a class in the sys module, but I don't think target comes from argv.
If you run type(target), you will get this: <_io.TextIOWrapper name='dde-recommendation-engine/sample_data/synthetic-micro/ratings.txt' mode='r' encoding='UTF-8'>
What that means in simple terms is that it is an object accessing that particular file (with only write permission because you have a w mode).
You can use this object to add stuff into the file by target.write(.....)
Do remember to close the file however by doing target.close() at the end.
Another way to do the same and I prefer this most of the times is:
with open(filename, 'w') as target:
target.write(...)
This way the file is closed automatically once you are out of the with context.
argv is the list populated by the arguments provided by user while running the program from shell. Please see https://docs.python.org/3/library/sys.html#sys.argv for more info on that.
User supplied the filename from shell, program used the open call https://docs.python.org/3/library/functions.html#open to get a file handle on that filename
And that file handle is stored in variable called target (which could be named anything you like) so that you can process the file using other file methods.
You are using open() - a built-in function in python. This function returns an File object - which is assigned to target variable. Now you can interact with target to write data (since you are using the w mode)
.
I need to 1) Find a zipfile at a particular directory location 2) If it exists then unzip it 3) Out of its contents find a specific file and move it to other directory.
def searchfile():
for file in os.listdir('/user/adam/datafiles'):
if fnmatch.fnmatch(file, 'abc.zip'):
return True
return False
if searchfile():
print('File exists')
else:
print('File not found')
def file_extract():
os.chdir('/user/adam/datafiles')
file_name = 'abc.zip'
destn = '/user/adam/extracted_files'
zip_archive = ZipFile (file_name)
zip_archive.extract('class.xlsx',destn)
print("Extracted the file")
zip_archive.close()
file_extract()
When I execute the above script, it shows no compile time issues or runtime issues,. but it just works for the first function. When I check for the files in the extracte_files folder I don't see the files.
So for the sake of completeness and as my comment solved your issue, I guess I should make it an Answer:
In Python, if a function foo is defined (def foo(<...>):),
foo refers to the function itself and can be copied around (effectively copying a pointer), passed to other functions, ... as about any object;
foo() is a call without passed argument to that function.
As this question does not seem to be an assignment, I will add the following:
To improve your code, you might want to look into:
Parameters to functions (you functions are currently only doing one single thing. For example, you could pass the file and directory names to searchfile);
os.path and all its content;
The in test for checking if an object is in a container;
The with statement for clearer and safer handling of objects such as ZipFile instances;
The x if b else y construst;
Notice that even if the archive does not exist, your code still attempts to extract a file from it.
Here is a more robust way to implement what you want:
import os
import zipfile
arch_name, file_name = 'abc.zip', 'class.xlsx'
home_dir = os.path.join(os.path.abspath(os.sep), 'user', 'adam')
# or even better: home_dir = os.path.expanduser('~')
arch_dir = os.path.join(home_dir, 'datafiles')
dest_dir = os.path.join(home_dir, 'extracted_files')
arch_path = os.path.join(arch_dir, arch_name)
if os.path.isfile(arch_path):
print('File {} exists'.format(arch_path))
with zipfile.ZipFile(arch_path) as archive:
archive.extract(file_name, dest_dir)
print('Extracted {} from {}'.format(file_name, arch_name))
else:
print('File {} not found'.format(arch_path))
Disclaimer: This code is untested and could contain minor mistakes!
Notice how the second half of the code works with generic variables that can easily be modified in a single place in the first half. Also, notice the improved readability of if os.path.isfile(arch_path): as opposed to if searchfile(): (requiring us to then read the implementation of searchfile).
There is a good chapter that will help with this in Automate the Boring Stuff
https://automatetheboringstuff.com/chapter9/
I have revised this question to make it much more simple.
I am running a program in python 3.x.
I want this program to open a file name example.py and run the code inside it.
This is the contents of the file:
#example1.py
print('hello world')
#example2.py
print('hello world 2')
#main.py
someMagicalCodeHere(executes example2.py)
#prints hello world
I need to do this without it being an imported file.
The problem with imported files is they are declared beforehand in the main.py. My main.py will be creating example1.py, example2.py etc and filling them with code, and then later referencing back to them as needed. There may be thousands or millions.
This is part of a large project that we are trying to switch over to a new language. We don't know python yet, and we need this concept to be viable to continue learning the language.
I have tried
exec(example.py)
I have tried
with open('example.py', 'r') as ex:
ex.read()
Thanks in advance for the answer, and thanks for all who have answered thus far.
I'm assuming you have some kind of a function that converts strings to such answers, or perhaps a dictionary. Otherwise the solution to this problem would be beyond the scope of current progress in NLP.
def ask_question_and_get_response(question=None):
answer = input(question)
return answer
I must also assume that you have a way to convert the original question, such as "What is your name?", to one that the user may in turn ask your bot, "What is my name?". Let that function look like what follows:
def get_reflex_question(question):
<your implementation>
return reflex_question
With both of these in hand, we can create a file (if one doesn't already exist), and write what can be interpreted as Python code to it.
def make_code(answer, reflex_question)
with open("filename", "a") as file:
file.write("\n")
file.write("if userBoxAsks == %s:\n\t" % (reflex_question))
file.write("print(answer)")
Which will output code to a file of your naming.
To run that file, you could use the subprocess module (read documentation), or simply import this file of yours as a module itself.
Whenever you update the file, you could reload the import so that the new code runs too. In Python3.x, you can do importlib.reload(filename) to refresh the import.
Alright after much deliberation, hunting and searching, I discovered through experimentation, found the answer to my own question.
#c:\\one.py
print('hello world')
#c:\\main.py
import os.path
filename = "c:\\one.py"
if not os.path.isfile(filename):
print ('File does not exist.')
else:
with open(filename) as f:
content = f.read().splitlines()
for line in content:
exec(line)
Returns (without quotes) 'Hello World'
Note that these solutions are not secure and considered risky. So obviously meant for play/test purpose
Python 2:
execfile('example2.py')
Python 3:
with open('example2.py') as f:
exec(f.read())
#view_config(route_name='home_page', renderer='templates/edit.pt')
def home_page(request):
if 'form.submitted' in request.params:
name= request.params['name']
body = request.params['body']
renderer_dict = dict(name=name,body=body)
new_comment = render('new_page.pt', renderer_dict, request=request)
with open('tutorial:templates/{name}.html','w') as file:
file.write(new_comment)
return HTTPFound(location=request.static_url('tutorial:pages/{pagename}.html',pagename=name))
return {}
Right now this is a view callable I have in my pyramid app that is for my apps home page. I am concerned about the line where file is created (with open...). I want the name of the file to be the same name defined by the request.params in the code above but I am not sure how to pass the variable (I doubt brackets are the right solution). I then want .html to be added to that name to make it a full file name. I am not sure what syntax to use in order to do this
Edit: I also would like advice on how to correctly do this on the return HTTPFound line. I would like it to redirect to that new file. Right now I have {pagename}.html but doubt that this is sufficient. I feel like the solution to this is the same as to the with open line but please correct me if Im wrong.
first off, i think you probably should NOT be doing whatever it is that you're trying to do.
second, to open the file...
name = request.params['name']
app_dir = SEE_BELOW
filename = "%(app_dir)s/templates/%(name)s" % { 'app_dir':app_dir , 'name':name }
filename = "%s/templates/%s" % ( app_dir , name )
with open(filename,'w') as file:
file.write(new_comment)
i'm going to note a few things:
app_dir - i forget how to get the actual pyramid app dir. i usually get spooked by this stuff, so only use specific subdirectories like such:
env.ini
templates_writable_dir = %(here)s/app/templates/writable/
then i can access it via:
request.registry.settings['templates_writable_dir']
note that i made a specific writable subfolder. i don't want the main stuff writable. i'll chmod/grp that writable folder so the user pyramid runs as can ed it. i won't allow that user to write to anything else.
"tutorial:templates/{name}.html" that is using the templated syntax, which only works in the templates. one of your pyramid plugins injects the renderer_dict into the template and renders it for you. you need to use normal python string formatting, as i showed above using two options.
More importantly...
based on your question, you're not just new to pyramid but to python too. i'd suggest doing a few quick python tutorials before jumping into Pyramid - or any other framework.
I don't think so that standard open understand tutorial:templtes and even {name}
use request.static_path there before use open
I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way.
Originally I was calling the execFile(<script_path>) function and then calling the function defined by executing the file. This has a side effect of always entering the if __name__ == "__main__" condition, which with my current setup I can't have happen.
I can't change the generated files, because I've already created 100's of them and don't want to have to revise them all. I can only change the file that calls the generated files.
Basically what I have now...
#<c:\File.py>
def func(word):
print word
if __name__ == "__main__":
print "must only be called from command line"
#results in an error when called from CallingFunction.py
input = sys.argv[1]
#<CallingFunction.py>
#results in Main Condition being called
execFile("c:\\File.py")
func("hello world")
Use
m = __import__("File")
This is essentially the same as doing
import File
m = File
If I understand correctly your remarks to man that the file isn't in sys.path and you'd rather keep it that way, this would still work:
import imp
fileobj, pathname, description = imp.find_module('thefile', 'c:/')
moduleobj = imp.load_module('thefile', fileobj, pathname, description)
fileobj.close()
(Of course, given 'c:/thefile.py', you can extract the parts 'c:/' and 'thefile.py' with os.path.spliy, and from 'thefile.py' get 'thefile' with os.path.splitext.)