2015-11-14 67 views
0

NetBeans中使用Python并将文件arguments设置为input/output有些麻烦。例如:Python:在NetBeans中传递文件作为输入

import re, sys 
for line in sys.stdin: 
    for token in re.split("\s+", line.strip()): 
     print(token) 

命令行用法python splitprog.py <input.txt> output.txt很好用。但是在NetBeans中,输出窗口只是等待,即使给出一个文件名(测试了很多组合),也不会发生任何事情。

项目属性中的Application Arguments行(其中一个可以为Java项目输入这些文件)似乎也没有使用,因为无论是否存在文件名/路径,行为都是相同的。是否有一些技巧可以使其发挥作用,或者在NetBeans中使用Python的文件参数目前无法使用?

ADD:按照建议通过@John Zwinck,一个例子溶液:

import re, sys 
with open(sys.argv[1]) as infile: 
    with open(sys.argv[2], "w") as outfile: 
     for line in infile: 
      for token in re.split("\s+", line.strip()): 
       print(token, file = outfile) 

参数文件是在NB项目属性设置。在命令提示符下,程序现在仅由python splitprog.py input.txt output.txt运行。

回答

1

当你这样做:

python splitprog.py <input.txt> output.txt 

您重定向到input.txtpythonstdinstdoutpythonoutput.txt。您根本没有使用命令行参数到splitprog.py

NetBeans does not support this.

相反,你应该通过文件名作为参数,就像这样:

python splitprog.py input.txt output.txt 

然后在NetBeans你刚才设置的命令行参数input.txt output.txt,也将努力同上述命令行在shell中。你需要稍微修改程序,也许是这样的:

with open(sys.argv[1]) as infile: 
    for line in infile: 
     # ... 

如果你仍然想支持stdinstdout,一个惯例是使用-意味着这些标准流,所以你可以在你的程序代码支持此:

python splitprog.py - - <input.txt> output.txt 

也就是说,你可以写你的程序,了解-为“从外壳使用标准流”,如果你需要支持做事的老办法。或者,如果没有给出命令行参数,就默认这种行为。

+0

非常丰富,谢谢!我试图根据您的解决方案编写代码,输出有点意外。我编辑了原始问题;你会介意检查代码吗? –

+1

@Россарх:你曾经使用'print',现在你正在使用'write',它不添加换行符。你可以做'print(token,file = outfile)'或'outfile.write(token +'\ n')'。 –

+0

完美的作品! –

相关问题