2

So I have a fully functional py script running on Ubuntu 12.04, everything works great. Except I don't like my input methods, it's getting annoying as you'll see below. Before I type out the code, I should say that the code takes two images in a .img format and then does computations on them. Here's what I have:

import os

first = raw_input("Full path to first .img file: ")
second = raw_input("Full path to second .img file: ")

print " "


if os.path.exists(first) == True:
    if first.endswith('.img') == False:
        print 'You did not give a .img file, try running again'
        os.sys.exit()
elif os.path.exists(second) == True:
    if second.endswith('.img') == False:
        print 'You did not give a .img file, try running again'
        os.sys.exit()
else:
    print "Your path does not exist, probably a typo. Try again"
    os.sys.exit()

Here's what I want; I want to be able to feed python this input straight from the Terminal. In other words, I want to be able to input in the terminal something like

python myscript.py with the two images as input

This way I could make use of the terminal's tab-key shortcut when specifying paths and stuff. Any ideas/suggestions?

EDIT: Ok so I looked into the parsing, and I think I got down how to use it. Here's my code:

import argparse

import nipy

parser = argparse.ArgumentParser()



parser.add_argument("-im", "--image_input", help = "Feed the program an image", type =     nipy.core.image.image.Image, nargs = 2)

however now I want to be able to use these files in the script by saying something like first = parser[0] second = parse[1] and do stuff on first and second. Is this achievable?

4

4 回答 4

7

您想在程序启动后解析命令行参数而不是读取输入。

为此使用argparse模块,或者sys.argv自己解析。

于 2013-07-04T16:08:13.663 回答
2

看到解析代码已经存在,您需要做的就是使用 Python 的sys 模块接受命令行参数:

import sys

first  = sys.argv[1]
second = sys.argv[2]

或者,更一般地说:

import os
import sys

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print('USAGE: python %s [image-paths]' % sys.argv[0])
        sys.exit(1)

    image_paths = sys.argv[1:]

    for image_path in image_paths:
        if not os.path.exists(image_path):
            print('Your path does not exist, probably a typo. Try again.')
            sys.exit(1)
        if image_path.endswith('.img'):
            print('You did not give a .img file, try running again.')
            sys.exit(1)

笔记

答案的第一部分为您提供了接受命令行参数所需的内容。第二部分介绍了一些处理它们的有用概念:

  1. 将 python 文件作为脚本运行时,全局变量__name__设置为'__main__'. 如果使用该if __name__ == '__main__'子句,则可以将 python 文件作为脚本运行(在这种情况下子句执行)或将其作为模块导入(在这种情况下不执行)。你可以在这里阅读更多关于它的信息。

  2. 如果脚本调用错误,通常会打印使用消息并退出。该变量sys.argv设置为命令行参数列表,它的第一项始终是脚本路径,因此len(sys.argv) < 2意味着没有传递任何参数。如果你想要两个参数,你可以len(sys.argv) != 3改用。

  3. sys.argv[1:]包含实际的命令行参数。如果你想要两个参数,你可以通过sys.argv[1]andsys.argv[2]来引用它们。

  4. 请不要使用if os.path.exists(...)==Trueandif string.endswith(...)==True语法。相反,它更清晰if os.path.exists,更 Pythonic 。if string.endswith(...)

  5. 不带参数使用exit()默认为exit(0),这意味着程序成功终止。如果您退出并显示错误消息,则应改用exit(1)(或其他一些非零值...)。

于 2013-07-04T17:56:57.390 回答
1

你想要做的是接受命令行参数,最好的方法是使用一个名为 argparse 的漂亮模块。我在下面列出了一个关于如何安装和使用它的好资源。

是 argparse 的一个很好的资源。它是一个用于获取命令行参数的模块。

于 2013-07-04T16:32:43.063 回答
0

您可能可以使用 sys.argv:

import sys

first = sys.argv[1]
second = sys.argv[2]

不要忘记len(sys.argv)之前检查。

于 2013-07-04T16:21:30.790 回答