Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Taking input in Python
Next article icon
A lot of people use Python as a replacement for shell scripts, using it to automate common system tasks, such as manipulating files, configuring systems, and so forth. This article aims to describe accepting Script Input via Redirection, Pipes, or Input Files.Problem -To have a script to be able to accept input using whatever mechanism is easiest for the user. This should include piping output from a command to the script, redirecting a file into the script, or just passing a filename, or list of filenames, to the script on the command line.Python’s built-infileinput module makes this very simple and concise if the script looks like this.Code #1 :Python3 1==
importfileinputwithfileinput.input()asf_input:forlineinf_input:print(line,end='')
Then input to the script can already be accepted in all of the previously mentioned ways. If the script is saved and make it executable then the one can get the expected output using all of the following:Code #2 :Python3 1==
# Prints a directory listing to stdout.$ ls | ./filein.py # Reads/etc/passwd to stdout.$ ./filein.py/etc/passwd # Reads/etc/passwd to stdout.$ ./filein.py < /etc/passwd
Thefileinput.input() function creates and returns an instance of theFileInput class. In addition to containing a few handy helper methods, the instance can also be used as a context manager. So, to put all of this together, if one wrote a script that expected to be printing output from several files at once, one might have it include the filename and line number in the output, as shown in the code given below -Code #3 :Python3 1==
importfileinputwithfileinput.input('/etc/passwd')asf:forlineinf:print(f.filename(),f.lineno(),line,end='')
/etc/passwd1/etc/passwd2/etc/passwd3 <other output omitted>
Using it as a context manager ensures that the file is closed when it’s no longer being used, and one leveraged a few handy FileInput helper methods here to get some extra information in the output.

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp