User input and command line arguments

2018-12-31 08:56发布

How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?

11条回答
裙下三千臣
2楼-- · 2018-12-31 09:25

The best way to process command line arguments is the argparse module.

Use raw_input() to get user input. If you import the readline module your users will have line editing and history.

查看更多
看风景的人
3楼-- · 2018-12-31 09:28

As of Python 3.2 2.7, there is now argparse for processing command line arguments.

查看更多
不再属于我。
4楼-- · 2018-12-31 09:31

Use 'raw_input' for input from a console/terminal.

if you just want a command line argument like a file name or something e.g.

$ python my_prog.py file_name.txt

then you can use sys.argv...

import sys
print sys.argv

sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"

If you want to have full on command line options use the optparse module.

Pev

查看更多
余生请多指教
5楼-- · 2018-12-31 09:32

In Python 2:

data = raw_input('Enter something: ')
print data

In Python 3:

data = input('Enter something: ')
print(data)
查看更多
若你有天会懂
6楼-- · 2018-12-31 09:33

If it's a 3.x version then just simply use:

variantname = input()

For example, you want to input 8:

x = input()
8

x will equal 8 but it's going to be a string except if you define it otherwise.

So you can use the convert command, like:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07
查看更多
登录 后发表回答