【问题标题】:Inserting User Inputted String into Linux commands [python script]?将用户输入的字符串插入 Linux 命令 [python 脚本]?
【发布时间】:2017-12-03 11:48:06
【问题描述】:

抱歉,如果这个问题是微不足道的,我是 python 的业余爱好者..

我目前正在尝试自动化一系列 linux 命令, 使用 python 脚本。 (具体涉及使用 ciao 命令下载和分析钱德拉望远镜数据)

简而言之,我的目标是脚本要求用户输入一个 5 字符长的数字字符串,该字符串存储为变量,随后插入到命令中,以便从脚本运行。

例如以下命令,其中星号将替换为用户输入的字符串。

import os
os.system("download_chandra_obsid *****")
os.chdir("usersc/####/Downloads/*****") 
os.system("dmkeypar acisf*****0N003_full_img2.fits dec echo=yes")

有没有简单的方法来实现这个?

提前谢谢...

【问题讨论】:

  • 如果您没有在代码中使用任何 Python 工具,那么将命令放在常规脚本中(cmd 或 Windows 的 Powershell;sh 或 Bash 用于U*x)。

标签: python linux string command


【解决方案1】:

使用number = input("Please type five digit number").strip() 从用户那里获取号码。如果你想检查它是否是一个有效的数字,使用这个结构:

while True:
    num = input("Please type five digit number").strip()
    if num.isdigit() and len(num) == 5:
         break

然后使用 .format() 和每个字符串在其中添加数字,如下所示:

os.system("download_chandra_obsid {0}".format(num))

(我认为这只适用于 python 2.6+)
有关str.format() 的更多详细信息,请参阅https://pyformat.info/#simplepython docs

【讨论】:

    【解决方案2】:
    import os
    
    user_inputted = input('Enter your string')
    # Perform validations on the input like length etc.
    os.system("download_chandra_obsid {}".format(used_inputted))
    os.chdir("usersc/####/Downloads/{}".format(used_inputted))
    os.system("dmkeypar acisf{}0N003_full_img2.fits dec echo=yes".format(used_inputted))
    

    【讨论】:

    • 根据您的评论(即使已删除)我已经测试了您的声明 os.system 无法识别 {}:os.system('echo {}'.format('hello world')) 打印 hello world
    • 感谢您的建议。在对此进行测试后,在我看来这不起作用,似乎是因为 os.system 命令不将 {} 识别为输入变量...例如,当我运行命令时 import.os Obsid = input('请输入 5 位观察 ID:') print(Obsid) os.system("donwload_chandra_obsid {}").format(Obsid)
    • 我收到以下终端错误“跳过 ObsID {},因为它在存档站点上找不到”
    • ) 符号之前添加您的格式。在关闭字符串 " 的双引号之后
    • 应该是这样的:os.system("donwload_chandra_obsid {}".format(Obsid))
    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 2022-01-02
    • 2011-09-13
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多