我知道这真的过时了,但你可以试试
#! /usr/bin/python
import sys
print(sys.argv, len(sys.argv))
if len(sys.argv) == 1:
message = input()
else:
message = sys.argv[1:len(sys.argv)]
print('Message:', message)
我因此对其进行了测试:
$ ./test.py
['./test.py'] 1
this is a test
Message: this is a test
$ ./test.py this is a test
['./test.py', 'this', 'is', 'a', 'test'] 5
Message: ['this', 'is', 'a', 'test']
$ ./test.py "this is a test"
['./test.py', 'this is a test'] 2
Message: ['this is a test']
$ ./test.py 'this is a test'
['./test.py', 'this is a test'] 2
Message: ['this is a test']
$ echo "This is a test" | ./test.py
['./test.py'] 1
Message: This is a test
或者,如果您希望消息每次都是一个字符串,那么
message = ' '.join(sys.argv[1:len(sys.argv)])
会在第 8 行做到这一点