简体   繁体   English

从命令行输入初始化Python对象

[英]Initialize a Python object from command line input

I'm new to Python and am learning input/output. 我是Python的新手,正在学习输入/输出。 Right now, I'm trying to add attributes to an object from a file that I specify from command line input. 现在,我正尝试从命令行输入中指定的文件中向对象添加属性。

For example, I want to run the following: $ /...filepath.../ python3 myCode.py < 06 to pass the contents of file 06 例如,我要运行以下命令: $ /...filepath.../ python3 myCode.py < 06以传递文件06的内容

$ /...filepath.../ cat 06
7
4 5 2 7 88 2 1

to myCode.py . myCode.py Both myCode.py and 06 are located in the same directory. myCode.py06都位于同一目录中。

I'm trying to create a MyClass object from a command line call with attributes to be as follows: 我正在尝试通过命令行调用创建一个MyClass对象,其属性如下:

## myCode.py ##

# create class
class MyClass(object):
    def __init__(self):
    self._num_one = int(sys.stdin.readline())    
    self._num_many = [int(x) for x in sys.stdin.readline().split()]

# print attributes
print(MyClass()._num_many)
print(MyClass()._num_one)

but I'm getting the following error ValueError: invalid literal for int() with base 10: '' for self._num_one but am able tor print self._num_many and am not sure why. 但是我收到以下错误ValueError: invalid literal for int() with base 10: ''self._num_oneValueError: invalid literal for int() with base 10: '' ,但能够打印出self._num_many ,不确定为什么。 If I swap the order of self._num_one and self.num_many , then I can get self._num_one . 如果我交换self._num_oneself.num_many的顺序,那么我可以得到self._num_one Since 06 is only two lines long, is there a first line that I'm not initially reading? 由于06只有两行,所以我最初没有读第一行吗? Why can I only print one of the two attributes, and how would I print both? 为什么我只能打印两个属性之一,我将如何打印两个属性?

Many thanks. 非常感谢。

just because your input stream is not an int, it's a string with space and "\\n" delimiter, you have to work on these things first. 仅仅因为您的输入流不是整数,而是带空格和“ \\ n”分隔符的字符串,所以您必须首先处理这些事情。

The quick and easy way is changing your code to something like this (not tested): 快速简便的方法是将您的代码更改为以下代码(未经测试):

self._num_one = int("".join(sys.stdin.readline().split()))

There are some problems with your code that stops it from working. 您的代码存在一些问题,导致其无法正常工作。

First thing first, you need to remove whitespace before and after if you are reading the input file one line after another. 首先,如果要逐行读取输入文件,则需要在前后删除空格。 This means a call to the .strip() method after .readline() . 这意味着对一个呼叫.strip()之后方法.readline() You are getting the ValueError because int() cannot process non-numeric string. 您正在获取ValueError因为int()无法处理非数字字符串。

>>> int('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'x'
>>> int(' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ' '
>>> int('\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '\n'
>>> int('1')
1

So the code becomes 所以代码变成

class MyClass(object):
    def __init__(self):
        self._num_one = int(sys.stdin.readline().strip())
        self._num_many = [int(x) for x in sys.stdin.readline().strip().split()]

Secondly, whenever you do MyClass() it instantiates a new object. 其次,每当执行MyClass()它都会实例化一个新对象。 If I understand the code correctly, it is expecting to read two lines twice (4 lines in total). 如果我正确理解该代码,则期望两次读取两行(总共4行)。 Given the input file, I am assuming you are interested in instantiating ONE object. 给定输入文件,我假设您对实例化一个对象感兴趣。 Therefore we instantiate one, and tag it to a variable, then use that reference later. 因此,我们实例化一个,并将其标记为变量,然后在以后使用该引用。

instantiatedObject = MyClass()
print(instantiatedObject._num_many)
print(instantiatedObject._num_one)

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

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