简体   繁体   中英

Python foo > bar(input file, output file)

It's propably very basic question but I couldn't find any answer. Right now I have something like:

import sys
inFile = sys.argv[1]
outFile = sys.argv[2]
with open(inFile, 'r+') as input,open(outFile,'w+') as out:
            #dosomething

I can run it with ./modulname foo bar (working). How can I change it so it will work with /.modulname foo > bar ? (right now it gives me following error).

./pagereport.py today.log > sample.txt
Traceback (most recent call last):
  File "./pagereport.py", line 7, in <module>
    outFile = sys.argv[2]
IndexError: list index out of range

You could skip the second open ( out ) and instead use sys.stdout to write to.

If you want to be able to use both ways of calling it, argparse has a comfortable way of doing that with add_argument by combining type= to a file open for writing and making sys.stdout its default.

When you do:

./modulname foo > bar

> is acted upon by shell, and duplicates the STDOUT stream (FD 1) to the file bar . This happens before the command even runs, so no, you can't pass the command like that and have bar available inside the Python script.

If you insist on using > , a poor man's solution would be to make the arguments a single string, and do some string processing inside, something like:

./modulname 'foo >bar'

And inside your script:

infile, outfile = map(lambda x: x.strip(), sys.argv[1].split('>'))

Assuming no filename have whitespaces, take special treatment like passing two arguments in that case.

Also, take a look at the argparse module for more flexible argument parsing capabilities.

What error have you got?

import sys
inFile = sys.argv[1]
outFile = sys.argv[2]
with open(inFile, 'r+') as in_put ,open(outFile,'w+') as out:
    buff = in_put.read()
    out.write(buff)

I try to run you code, but you have no import sys , so after fixed it as above . I can run it as a simple cp command.

python p4.py p4.py p4.py-bk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM