【问题标题】:Python in windows : programming from the command lineWindows 中的 Python:从命令行编程
【发布时间】:2014-06-28 09:59:25
【问题描述】:

我想从 cmd 用 python 编写简单的多行程序,我想做的是传递一个参数然后做一些操作并将输出保存到文本文件,我在网上找到了一些例子,但没有什么对我有用.
例如,这是我想做的事情:
>echo "230-20-5" | python -c "[commands]" > output.txt
我想拆分它,取每个数字并在每个数字上加 5,然后将结果相加,因此 output.txt 应该是:
235 25 10 the result is : 270

顺便说一句,如果有人可以在线给我一个教程,那就太好了
谢谢。

【问题讨论】:

  • 为什么要这样做?为什么不编写一个实际的 Python 脚本,或者使用命令行已经提供的工具?
  • 因为在 windows 命令中使用管道会很棒:)
  • 我想你总是可以从命令行运行 python 脚本!
  • 是的,但不一样,这个方法可以让你节省时间
  • 您是在问“[commands]”中有什么内容,或者您​​如何在 Windows 中进行 i/o 重定向?

标签: python windows command-line


【解决方案1】:

是的,我在问 [commands] 中的内容,我知道如何执行简单的单行命令,例如 >python -c "p​​rint 'Hello' " > output.txt 但不是多行命令

不知道你为什么要这样做,但是你去吧:

>> 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 将包含:

235
25
10
the result is: 270

我使用 bash 对此进行了测试,因此您可能需要对在 windows 下使用的任何 shell 进行微调。

【讨论】:

  • 对我不起作用Traceback (most recent call last): File "<string>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1 \"230-20-5\" ^ SyntaxError: unexpected character after line continuation character
  • @user2776193 是的,这可能是因为您必须在 shell 中以不同的方式转义 " 和 '。但一般的方法是使用 exec("command1\ncommand2"),将命令与 \n 分开。
  • 好的,要让它在 Windows 上工作,你只需要像这样echo "230-20-5" | .... 从 echo 中删除逃生包
  • 现在我可以从命令行使用 python,我不会再错过 bash 命令行 sed、grep 和 awk 等。 :)
【解决方案2】:

将以下代码放入文件中,比如 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

现在从命令行输入:

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

您也可以尝试直接使用以下代码:

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

虽然我无法让它工作!!!

【讨论】:

  • 谢谢,但我不想使用脚本,我想从命令行进行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 2016-05-22
  • 1970-01-01
相关资源
最近更新 更多