0

So if the user is running my file (test.py) from the command line, and wants to open a file in that program, how do I open it?

Say if the user writes 'test.py < file2.py' in command line, how do I then open file2.py in test.py?

I know it's something to do with sys.argv.

PierreTroodoo
  • 171
  • 1
  • 1
  • 4
  • `<` will pipe `file2.py` into `sys.stdin` (which you could read from inside `test.py`, if you wanted) -- alternatively, `test.py file2.py` will call `test.py` with an *argument* of `file2.py` which you can access with `sys.argv`. – jedwards Mar 20 '15 at 03:10

2 Answers2

1

you need to use sys.argv

sys.argv

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

it should be :

python test.py your_file

sys.argv[0], its the script name that is test.py

sys.argv[1], will have your_file

now you can use open built-in to open file:

my_file = open(sys.argv[1], 'r')

suppose you entered the file and number both:

python test.py your_file 2

here : sys.argv[0] -> test.py

sys.argv[1] -> your_file

sys.argv[2] -> number that is 2

Community
  • 1
  • 1
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
  • Let's say that the user can enter a number of specifiers in command line, and the location of the file itself can change in the index. In that case, I can't specify the exact number []... – PierreTroodoo Mar 20 '15 at 03:26
0

Hackaholic's answer is pretty good. However, if you just want to redirect input from file using "< file2.py", then you can use raw_input.

Note that redirecting the input essentially means that the input is available on stdin and you can read it using raw_input. I found this example which is similar to what you are trying:

while True:
  try:
    value = raw_input()
    do_stuff(value) # next line was found 
  except (EOFError):
    break #end of file reached

Update: Even more elegant would be to use the solution provided here:

import sys

for line in sys.stdin:
    do_something()
Community
  • 1
  • 1
Turbo
  • 2,179
  • 18
  • 38