如何在Python的os.system中包装shell命令?

时间:2013-02-11 09:56:43

标签: python shell

它可以获取名为myFile.txt的文件,其中的内容为:

file  '/home/debian/1.flv'  
file  '/home/debian/2.flv'  
file  '/home/debian/3.flv'  
file  '/home/debian/4.flv'  
file  '/home/debian/5.flv'  

现在我想用Python包装它

os.system("seq  --format="file  '/home/debian/%G.flv'" 5 > myFile.txt" )    
File "<stdin>", line 1  
os.system("seq  --format="file  '/home/debian/%G.flv'" 5 > myFile.txt" )  
                             ^
SyntaxError: invalid syntax

如何用Python包装?

  1. 我明白如何用Python创建文件(kvivek)

  2. 我的目标是了解如何在Python中使用复杂的shell命令,
    如果行数是变量?

  3. 还有问题
    1. @Torxed转义字符方式

      >>> i=7    
      >>> os.system("seq --format=\"file '/home/debian/%G.flv'\" %d > myFile.txt" %i )  
      Traceback (most recent call last):  
        File "<stdin>", line 1, in <module>  
      TypeError: float argument required, not str  
      
    2. @ganachoco's三重引号方式

      >>> os.system('''seq  --format="file  '/home/debian/%G.flv'" %d > myFile.txt" %i''')  
      sh: 1: Syntax error: Unterminated quoted string
      
    3. 有两个要考虑的状态, 状态1: 变量在shell中,我们可以做(我已经验证了以下两个shell命令)

      root@debian:/home/debian# i=7
      root@debian:/home/debian# seq --format="file '/home/debian/%G.flv'" $i > myFile.txt
      

      如何使用os.system将其包装在Python中?

      >>> os.system('i=7')
      0
      >>> os.system("seq --format=\"file '/home/debian/%G.flv'\" $i > myFile.txt")
      seq: missing operand
      Try `seq --help' for more information.
      256
      

      变量在Python中,现在我想调用shell命令将Python中的变量放入shell中,我该怎么办?

      >>> i=7  #in python prompt
      >>> os.system("seq --format=\"file '/home/debian/%G.flv'\" `here i want to get value from python prompt` > myFile.txt")
      

3 个答案:

答案 0 :(得分:3)

引用“反斜杠

for i in (range(1,5)):
    os.system("seq  --format=\"file  '/home/debian/%d.flv'\" > myFile.txt" %i )

答案 1 :(得分:3)

使用三重报价

os.system("""seq  --format="file  '/home/debian/%G.flv'" 5 > myFile.txt""")

答案 2 :(得分:0)

希望这给你正在寻找的东西

[root@localhost ~]# python
Python 2.6.6 (r266:84292, Apr 11 2011, 15:50:32)
[GCC 4.4.4 20100726 (Red Hat 4.4.4-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> cmdstr = """i=7 && seq --format="file '/home/kvivek/%G.flv'" $i > myFile.txt"""
>>> os.system(cmdstr)
0
>>> exit()
[root@localhost ~]# cat myFile.txt
file '/home/kvivek/1.flv'
file '/home/kvivek/2.flv'
file '/home/kvivek/3.flv'
file '/home/kvivek/4.flv'
file '/home/kvivek/5.flv'
file '/home/kvivek/6.flv'
file '/home/kvivek/7.flv'
[root@localhost ~]#