简体   繁体   English

Windows中的Python:从命令行进行编程

[英]Python in windows : programming from the command line

I want to to write simple multi line programs in python from the cmd, what I want to do is to pass an argument then do some manipulations and save output to text file, I found some examples online but nothing is working for me. 我想从cmd用python编写简单的多行程序,我想做的是传递一个参数,然后进行一些操作并将输出保存到文本文件,我在网上找到了一些示例,但没有任何帮助。
for example here is somthing that I want to do: 例如,这里是我想做的事情:
>echo "230-20-5" | python -c "[commands]" > output.txt
I want to split it, take each number and add 5 to each one then sum the results so the output.txt should be: 我想将其拆分,取每个数字,然后将每个数字加5,然后对结果求和,因此output.txt应该是:
235 25 10 the result is : 270

By the way, If someone can give me a tutorial online that would be great 顺便说一句,如果有人可以给我在线教程,那将是很棒的
thanks. 谢谢。

Yes,I am asking what has to go in [commands], I know how to do simple one line commands like >python -c "print 'Hello' " > output.txt but not multiple lines commands 是的,我问[命令]中必须包含什么内容,我知道如何执行简单的单行命令,例如> python -c“ print'Hello'”> output.txt,但不能执行多行命令

No idea why you want to do this, but here you go: 不知道为什么要这样做,但是在这里您可以:

>> echo "230-20-5" | python2.7 -c "exec(\"inp=raw_input()\nlst=[int(x)+5 for x in inp.split('-')]\nfor x in lst: print x\nprint \'the result is:\', sum(lst)\")" > out

out will contain: out将包含:

235
25
10
the result is: 270

I tested this with bash, so you might need minor adjustments for whatever shell you are using under windows. 我使用bash进行了测试,因此您可能需要对Windows下使用的任何shell进行少量调整。

Put the following code in a file say foo_bar.py 将以下代码放在文件foo_bar.py中

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("val")
args = parser.parse_args()

for i in args.val.split('-'):
    print int(i) + 5
    sum += int(i) + 5
print 'the result is', sum

Now from command line type: 现在从命令行输入:

python foo_bar.py 230-20-5  > output.txt

You can try putting the code directly as well using: 您也可以尝试使用以下方法直接放置代码:

python -c "import argparse;parser = argparse.ArgumentParser();parser.add_argument('val');args = parser.parse_args();for i in args.val.split('-'):print int(i) + 5;" 230-20-5 > output.txt

Although I could not get it to work!!! 虽然我无法正常工作!

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

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