简体   繁体   English

将BASH脚本更改为Python

[英]Changing BASH script to Python

I am trying to convert this script to Python but am having problems with the BASH syntax ${variable} . 我正在尝试将此脚本转换为Python,但BASH语法${variable}遇到问题。 This does something I do not understand as I have very little experience with BASH scripting. 这是我不了解的事情,因为我对BASH脚本的了解很少。 My question is basically,how can I do the dollar brackets variable thing in Python ${variable} . 我的问题基本上是,如何在Python ${variable}进行美元括号变量操作。 In my case the variable is a number from zero to two-hundred and fifty-five. 在我的情况下,变量是一个从零到200到55的数字。 Please see the BASH script below. 请参阅下面的BASH脚本。 I am trying to do the exact same thing in Python. 我正在尝试在Python中做同样的事情。

do     

    for code in {0..255};        
        do echo -e "\e[38;05;${code}m $code: Test";        
        done; 

done

Here is my attempt to convert the code to a Python script. 这是我尝试将代码转换为Python脚本的尝试。 Unfortunately, I am still having to call BASH via the os.system() method or function. 不幸的是,我仍然必须通过os.system()方法或函数来调用BASH。 Please check out my script below. 请在下面查看我的脚本。 The script does not function the same way though, with changing the text in the BASH shell. 但是,该脚本的功能与BASH Shell中的文本更改不同。 The Python script below simply prints out the crazy text below and increments the numbers... :/ 下面的Python脚本只是在下面打印出疯狂的文本并增加数字...:/

#! /usr/bin/env python

import os

def run():
    for code in range(0, 255):
        os.system('echo -e "\e[38;05;%dm %s Test"' % (code,str(code)))



run()

You can use print command and string formatting to evaluate your variable during the print. 您可以在打印过程中使用print命令和字符串格式来评估变量。

BTW, you can use xrange rather than range in order not to generate all the numbers in your memory, but to yield it one-by-one (for large range) 顺便说一句,你可以使用xrange而不是range ,以便不产生在你的记忆所有的数字,但对yield它一个接一个(大范围)

You can use this: 您可以使用此:

import os
def run():
   for code in range(0, 256):
     print "\x1b[38;05;{code}m {code} Test".format(code=code)

run()

You'll need to use string formatting . 您需要使用字符串格式

Strangely enough, you already do this in your code (but using the old % syntax instead of the new .format method). 奇怪的是,您已经在代码中执行了此操作(但是使用旧的%语法而不是新的.format方法)。 I'm not even sure why you think you have to call echo since the string you pass to it is already the string that you are trying to get (if I understand your question right). 我什至不确定您为什么认为您必须调用echo因为传递给它的字符串已经是您要获取的字符串(如果我理解正确的话)。 Just use the print function to output the string. 只需使用print功能来输出字符串。

try this: 尝试这个:

#! /usr/bin/env python

import os

def run():
    for code in range(0, 255):
        os.system('/bin/echo -e "\e[38;05;%dm %s Test"' % (code,str(code)))



run()

the echo is usually both extrnal program and internal command of shell, which can make difference sometime echo通常既是外部程序又是shell的内部命令,有时可能会有所不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM