How to redirect 'print' output to a file using python?
how to redirect a url to another url in html
how to redirect a domain
how to redirect a url in wordpress
url redirect service
redirect on page load
I want to redirect the print to a .txt file using python. I have a 'for' loop, which will 'print' the output for each of my .bam file while I want to redirect ALL these output to one file. So I tried to put
f = open('output.txt','w'); sys.stdout = f
at the beginning of my script. However I get nothing in the .txt file. My script is:
#!/usr/bin/python import os,sys import subprocess import glob from os import path f = open('output.txt','w') sys.stdout = f path= '/home/xug/nearline/bamfiles' bamfiles = glob.glob(path + '/*.bam') for bamfile in bamfiles: filename = bamfile.split('/')[-1] print 'Filename:', filename samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile], stdout=subprocess.PIPE,bufsize=1) linelist= samtoolsin.stdout.readlines() print 'Readlines finished!' ........print.... ........print....
So what's the problem? Any other way besides this sys.stdout?
I need my result look like:
Filename: ERR001268.bam Readlines finished! Mean: 233 SD: 10 Interval is: (213, 252)
The most obvious way to do this would be to print to a file object:
with open('out.txt', 'w') as f: print >> f, 'Filename:', filename # Python 2.x print('Filename:', filename, file=f) # Python 3.x
However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:
import sys orig_stdout = sys.stdout f = open('out.txt', 'w') sys.stdout = f for i in range(2): print 'i = ', i sys.stdout = orig_stdout f.close()
Redirecting externally from the shell itself is another good option:
./script.py > out.txt
What is the first filename in your script? I don't see it initialized.
My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.
Also, use os.path.join and os.path.basename to manipulate paths and filenames.
How to Redirect a Web Page, A redirect is when a web page is visited at a certain URL, it changes to a different URL. For instance, a person visits “website.com/page-a” in their browser and Using a Redirection Service 1. Check with your web host. If you're unsure of your own coding ability or just want to redirect a URL without digging 2. Pick a 3rd party service. If your web host doesn't offer redirection, there are many other options out there. 3. Follow the instructions from the
You can redirect print with the
f = open(filename,'w') print >>f, 'whatever' # Python 2.x print('whatever', file=f) # Python 3.x
In most cases, you're better off just writing to the file normally.
or, if you have several items you want to write with spaces between, like
f.write(' '.join(('whatever', str(var2), 'etc')))
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The file argument must be an object with a
write(string)method; if it is not present or
sys.stdoutwill be used. Since printed arguments are converted to text strings,
print()cannot be used with binary mode file objects. For these, use
Write/Overwrite to File
with open('file.txt', 'w') as f: print('hello world', file=f)
Write/Append to File
with open('file.txt', 'a') as f: print('hello world', file=f)
How to Redirect a Domain: A Complete Guide for Beginners, Want to know how to redirect a domain properly? Check out this step-by-step guide and learn about the types of redirects you can choose from. Click “Go”. After a new tab or window opens, look for the .htaccess file. Right click on the .htaccess file and click on “Code Edit” on the menu. A dialogue box may pop up asking about encoding. Click “Edit” button to continue. Edit the file. “Save Changes” when done.
This works perfectly:
import sys sys.stdout=open("test.txt","w") print ("hello") sys.stdout.close()
Now the hello will be written to the test.txt file. Make sure to close the
stdout with a
close, without it the content will not be save in the file
How to Redirect a URL, URL redirects are a normal and often desirable part of hosting a website or building a web application. A URL redirect (also known as a domain redirect, web The simplest way to redirect to another URL is to use an HTML <meta>tag with the http-equiv parameter set to “refresh”. The "content" attribute sets the delay before the browser redirects the user to the new web page. To redirect immediately, set this parameter to “0” seconds for the "content"attribute.
You can change
sys.stdout to point to a file, but this is a pretty clunky and inflexible way to handle this problem. Instead of using
logging, you can print just like you would to
stdout, or you can also write the output to a file. You can even use the different message levels (
debug) to, for example, only print major issues to the console, but still log minor code actions to a file.
A simple example
logging, get the
logger, and set the processing level:
import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) # process everything, even if everything isn't printed
If you want to print to stdout:
ch = logging.StreamHandler() ch.setLevel(logging.INFO) # or any other level logger.addHandler(ch)
If you want to also write to a file (if you only want to write to a file skip the last section):
fh = logging.FileHandler('myLog.log') fh.setLevel(logging.DEBUG) # or any level you want logger.addHandler(fh)
Then, wherever you would use
# print(foo) logger.debug(foo) # print('finishing processing') logger.info('finishing processing') # print('Something may be wrong') logger.warning('Something may be wrong') # print('Something is going really bad') logger.error('Something is going really bad')
To learn more about using more advanced
logging features, read the excellent
logging tutorial in the Python docs.
How To Redirect a URL - Website Redirect, URL redirect (URL forwarding) allows you to forward your domain visitors to any URL of your choice. This guide provides steps on how to redirect a URL for a In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3, and a Location header holding the URL to redirect to. When browsers receive a redirect, they immediately load the new URL provided in the Location header. Besides the small performance hit of an additional round-trip, users rarely notice the redirection.
URL redirection, URL redirection, also called URL forwarding, is a World Wide Web technique for making a web page available under more than one URL address. When a web Use a redirect service The simplest option to perform an HTTPS redirect is to use a redirection service. DNSimple provides a redirector service you can use to redirect HTTPS requests. Using a service is the simplest solution, because it requires little configuration and almost no technical knowledge.
- Why not use
- yeah, but I have several data for each bam file (mean, SD,interval...), how can I put these data one by one?
f.write(line)- it inserts a line break at the end.
- @Eran Zimmerman:
f.write(line)does not add a line break to the data.
- You're right, my bad. Could always
- Line 8 of your code uses a variable named filename, but it hasn't been created yet. Later in the loop you use it again, but not relevant.
- Bad practice to change sys.stdout if you don't need to.
- @my I'm not convinced it is bad for a simple script like this.
- +1 Haha well you can have my upvote because it's the right way to do it if you absolutely must do it the wrong way... But I still say you should do it with regular file output.
- How to redirect and print the output on the console ? Seems the "print()" in Python cannot be shown when the stdrr is redirected ?