【问题标题】:How to obtain a python command line argument if only it's a string如果只有字符串,如何获取python命令行参数
【发布时间】:2019-12-12 18:57:02
【问题描述】:

我正在制作自己的 python CLI,我只想传递 String 参数

import sys
import urllib, json
# from .classmodule import MyClass
# from .funcmodule import my_function
def main():

    args = sys.argv[1:]
    #print('count of args :: {}'.format(len(args)))
    #for arg in args:
     #   print('passed argument :: {}'.format(arg))


    #always returns true even if i don't pass the argument as a "String"
    if(isinstance(args[0], str)): 
        print('JSON Body:')
        url = args[0]
        response = urllib.urlopen(url)
        data = json.loads(response.read())
        print(data)

    # my_function('hello world')
    # my_object = MyClass('Thomas')
    # my_object.say_name()
if __name__ == '__main__':
    main()

我通过api "url" 执行它,这是正确的输出:

虽然当我尝试执行 api url 而不将其作为 String 传递时,我的输出有点奇怪:

我怎样才能只接受String 参数?

到目前为止我已经尝试过:

  • 找到了这个解决方案 here,但它对我不起作用(无法识别 join() 函数)

【问题讨论】:

标签: python python-3.x


【解决方案1】:

问题不是 python 问题。只是您的 URL 包含 &,并且在 linux/unix shell 上,这要求在后台运行您的命令(并且删除 & 之后的数据)。这解释了 [1]+ done 输出,以及截断的命令行。

所以你必须引用你的论点以避免它被解释(或使用\&)。 Un*x shell 无法解决这个问题(例如,它可以在 Windows shell 中不加引号地工作)

【讨论】:

  • 基本没有办法知道参数是不是strings ?
  • python 甚至看不到命令​​行的其余部分。这是一个外壳问题。 python帮不上忙
  • @PhillAlexakis 参数 (sys.argv) 始终是字符串
猜你喜欢
  • 1970-01-01
  • 2019-12-24
  • 2016-10-06
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2017-12-10
相关资源
最近更新 更多