How to write help() documentation to a file Python? [duplicate] - python

This question already has answers here:
How do I export the output of Python's built-in help() function
(11 answers)
Closed 4 years ago.
So I was looking at the help() documentation of a module but soon realized it was very tedius to read the documentation in the small output box. So therefore I tried pasting the help() documentation to another file for more clearer reading.
myfile = open("file.txt","w")
myfile.write(str(help(random)))
myfile.close()
Instead of the documentation being written, it instead pasted in None.
Any ideas how to do this?

The answer is pydoc!. Run it from the console:
$ pydoc [modulename] > file.txt
and it will basically write the output of the help() command to file.txt

i'm not suggesting you should read the python documentation this way - but here is what you could do: you could redirect stdout and call help:
from contextlib import redirect_stdout
import random
with open('random_help.txt', 'w') as file:
with redirect_stdout(file):
help(random)
or, even simpler (as suggested by Jon Clements):
from pydoc import doc
import random
with open('random_help.txt', 'w') as file:
doc(random, output=file)

Related

Curl command with options in Python 3 [duplicate]

This question already has answers here:
Python basics - request data from API and write to a file
(2 answers)
Closed 2 years ago.
In requests library, if you need to execute
curl http://www.example.com/file.xlsx
The command is
response = requests.get('http://www.example.com/file.xlsx')
What If I want to execute the command with -O option?
curl http://www.example.com/file.xlsx -O
How do I achieve that?
There's no explicit "-O" = write to the same filename.
You if you need that, you can store the url in a variable
and use several ways of getting it. A lazy way is using rpartition('/')[2] on
the url string.
The rest of the code to quickly save the result is here:
import requests
from pathlib import Path
response = requests.get('http://www.example.com/file.xlsx')
Path('file.xlsx').write_bytes(response.content)
# or if you want to have the file name extracted use this less readable line
# Path(response.url.rpartition('/')[2]).write_bytes(response.content)
To achieve the use case of CURL's -O option in Python, you have to write few lines of code like,
import requests
r = requests.get('https://your.url.com/path')
with open('path.txt','w') as fd:
fd.write(r.text)
I'm not sure requests supports a flag for this purpose. However, you can try doing something like:
from pathlib import Path
p = Path('http://www.example.com/file.xlsx')
r = requests.get(str(p))
Path(p.name).write_bytes(r.content)

Sending print output to a file in Python script [duplicate]

This question already has answers here:
Correct way to write line to file?
(17 answers)
Closed 7 years ago.
How would I go about sending the output of a print command to a new file? I have a python script where I need to redirect the output at the end of the print statement to a file but I can't seem to find a way to accomplish the redirect. Why doesn't "print (stuff to be redirected) > newfile.txt" work?
Any help is appreciated!
As mentioned in this post, you could set the standard output to a file object.
import sys
sys.stdout = open('file', 'w')
Then, all your print statements should go directly to that file.

How to Accept Command Line Arguments With Python Using < [duplicate]

This question already has answers here:
Python command line 'file input stream'
(3 answers)
Closed 8 years ago.
Is it possible to run a python script and feed in a file as an argument using <? For example, my script works as intended using the following command python scriptname.py input.txt and the following code stuffFile = open(sys.argv[1], 'r').
However, what I'm looking to do, if possible, is use this command line syntax: python scriptname.py < input.txt. Right now, running that command gives me only one argument, so I likely have to adjust my code in my script, but am not sure exactly how.
I have an automated system processing this command, so it needs to be exact. If that's possible with a Python script, I'd greatly appreciate some help!
< file is handled by the shell: the file doesn't get passed as an argument. Instead it becomes the standard input of your program, i.e., sys.stdin.
When you use the < operator in a shell you are actually opening the file and adding its contents to your scripts stdin
However there is is a python module that can do both. It's called fileinput.
https://docs.python.org/2/library/fileinput.html
It was shown in this post
How do you read from stdin in Python?
You can use the sys module's stdin attribute as a file like object.

How do I use the < > commands in my program? [duplicate]

This question already has answers here:
How do I read from stdin?
(25 answers)
Closed 18 days ago.
I have written a program that calculates the counts of each word in an input file. At the moment I am getting the filename using sys.argv[1], but I am actually supposed to be using
python word_counts.py < homer.txt > homer.test
I think homer.txt is the input file that is directed to my python script, while homer.test is the file that the output of my script is written to.
How do I make these work in my program?
The information in homer.txt is provided on standard-in. In python, that is a file handle called sys.stdin:
import sys
for line in sys.stdin: # reads from homer.txt
# process line
print(output) # writes to homer.test
homer.test is collecting data from standard-out. In python, the print statement writes to stdout by default. If you want to treat it explicitly as a file handle, you can use sys.stdout.
Use sys.stdin to read from homer.txt and sys.stdout (or print) to write to homer.test.

Unix cat function (cat * > merged.txt) in Python? [duplicate]

This question already has answers here:
Reproduce the Unix cat command in Python
(6 answers)
Closed 9 years ago.
Is there a way to use the cat function from Unix in Python or something similar once a directory has been established ? I want to merge files_1-3 together into merged.txt
I would usually just find the directory in Unix and then run
cat * > merged.txt
file_1.txt
file_2.txt
file_3.txt
merged.txt
Use the fileinput module:
import fileinput
import glob
with open('/path/to/merged.txt', 'w') as f:
for line in fileinput.input(glob.glob('/path/to/files/*')):
f.write(line)
fileinput.close()
As we know we are going to use "Unix" cat command (unless you are looking for a pythonic way or being performance concious)
You can use
import os
os.system("cd mydir;cat * > merged.txt")
or
as pointed by 1_CR (Thanks) and explained here
Python: How to Redirect Output with Subprocess?
Use fileinput. Say you have a python file merge.py with the following code, you could call it like so merge.py dir/*.txt. File merged.txt gets written to current dir. By default, fileinput iterates over the list of files passed on the command line, so you can let the shell handle globbing
#!/usr/bin/env python
import fileinput
with open('merged.txt', 'w') as f:
for line in fileinput.input():
f.write(line)

Categories

Resources