0

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!

Fred Foo
  • 342,876
  • 71
  • 713
  • 819
AvocadoRivalry
  • 411
  • 1
  • 7
  • 16

3 Answers3

1

< 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.

Fred Foo
  • 342,876
  • 71
  • 713
  • 819
0

You can use the sys module's stdin attribute as a file like object.

Russia Must Remove Putin
  • 337,988
  • 84
  • 391
  • 326
mobiusklein
  • 1,393
  • 8
  • 12
0

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?

Community
  • 1
  • 1
user1658078
  • 122
  • 5