【问题标题】:how to send string to python file and display it using terminal如何将字符串发送到python文件并使用终端显示它
【发布时间】:2021-11-09 06:13:06
【问题描述】:

我想知道如何从terminalcommand prompt 获取string 并将该字符串设为小写并将其显示在terminalcommand prompt
我使用了此代码,但不是工作

// in main.py cmd or terminal

import sys
tdf = sys.argv[1]
print(tdf)

terminal

// in cmd or terminal

PS E:\Python\Project\At> python .\main.py "Hi"

当我在终端中使用它时,我得到了这个错误

文件“C:\Users\miladm\AppData\Local\Programs\Python\Python39\lib\encodings\cp1256.py”,第 19 行,编码 返回 codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError:“charmap”编解码器无法在位置 13 编码字符“\u06cc”:字符映射到

【问题讨论】:

  • 我很难重现此错误,您能否提供更多有关您的 python 版本、操作系统等的信息?

标签: python


【解决方案1】:

代码:

import sys

print ("Data from terminal :",sys.argv)

在运行脚本时使用:

D:\python>python cmdline.py "hello"

输出:

Data from terminal : ['cmdline.py', 'hello']

【讨论】:

    【解决方案2】:

    运行 python filename.py "arguments"

    而不是

    tdf = sys.argv[1]
    

    使用,

    tdf = sys.argv[-1]
    

    因为它将获取命令行上的最后一个参数。如果没有传递参数,它将是脚本名称本身,因为 sys.argv[0] 是正在运行的程序的名称。在您的情况下,如果没有传递参数,则会产生错误

    import sys
    tdf = sys.argv[-1]
    print(tdf)
    

    【讨论】:

      【解决方案3】:

      要读取用户输入,您可以尝试使用thecmdmodule 轻松创建迷你命令行解释器(带有帮助文本和自动完成功能)和raw_input(Python 3+ 的输入)用于读取一行来自用户的文本。

      text = raw_input("prompt")  # Python 2
      text = input("prompt")  # Python 3
      

      命令行输入在 sys.argv 中。在你的脚本中试试这个:

      import sys
      print (sys.argv)
      

      有两个模块用于解析命令行选项:optparse(自 Python 2.7 起已弃用,请改用 argparse)和 getopt。如果您只是想将文件输入到您的脚本中,看看 fileinput 的强大功能吧。

      【讨论】:

        猜你喜欢
        • 2017-12-28
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 2017-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多