是否将用户输入的字符串插入Linux命令[python脚本]?
抱歉,如果这个问题很琐碎,我是python的业余爱好者 我目前正在尝试自动化一系列linux命令, 使用python脚本。(特别是使用ciao命令下载和分析钱德拉望远镜数据) 简而言之,我的目标是脚本要求用户输入一个5个字符长的数字字符串,该字符串作为变量存储,然后插入到命令中,从脚本运行 例如,以下命令,其中星号将由用户输入的字符串替换是否将用户输入的字符串插入Linux命令[python脚本]?,python,linux,string,command,Python,Linux,String,Command,抱歉,如果这个问题很琐碎,我是python的业余爱好者 我目前正在尝试自动化一系列linux命令, 使用python脚本。(特别是使用ciao命令下载和分析钱德拉望远镜数据) 简而言之,我的目标是脚本要求用户输入一个5个字符长的数字字符串,该字符串作为变量存储,然后插入到命令中,从脚本运行 例如,以下命令,其中星号将由用户输入的字符串替换 import os os.system("download_chandra_obsid *****") os.chdir("us
import os
os.system("download_chandra_obsid *****")
os.chdir("usersc/####/Downloads/*****")
os.system("dmkeypar acisf*****0N003_full_img2.fits dec echo=yes")
等
有没有一个简单的方法来实现这一点
提前感谢…使用
number=input(“请键入五位数”).strip()从用户处获取号码。如果要检查它是否为有效数字,请使用以下结构:
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))
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()
的更多详细信息,请参见您的评论(即使已删除),我已经测试了您的声明操作系统不会识别{}: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))
如果您的代码中没有使用任何Python工具,那么只需将命令放在常规脚本中(cmd
或Powershell for Windows;sh
或Bash for U*x)就不会那么笨重了。