简体   繁体   English

Python foo> bar(输入文件,输出文件)

[英]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). 我可以用./modulname foo bar (工作)来运行它。 How can I change it so it will work with /.modulname foo > bar ? 如何更改它以便它可以与/.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. 您可以跳过第二个打开( out ),而是使用sys.stdout写入。

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. 如果你想能够使用这两种方法调用它, argparse可以通过将type=组合到一个打开的文件并将sys.stdout为默认值来使用add_argument来实现这一目的。

When you do: 当你这样做时:

./modulname foo > bar

> is acted upon by shell, and duplicates the STDOUT stream (FD 1) to the file bar . >由shell执行操作,并将STDOUT流(FD 1)复制到文件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. 这在命令运行之前发生,所以不,你不能传递这样的命令并在Python脚本中有可用的bar

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. 另外,请查看argparse模块以获得更灵活的参数解析功能。

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 . 我尝试运行你的代码,但你没有import sys ,所以在修复它之后如上所述。 I can run it as a simple cp command. 我可以将它作为一个简单的cp命令运行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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