2013-02-11 58 views
0

它可以得到一個名爲myFile.txt文件,其中內容是:如何在python的os.system中包裝shell命令?

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命令,
    如果行數是變量?

還有與

  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 
    

有兩種居留制來算, 狀態1: 變量是在shell中,我們可以做(我覈實了以下拖shell命令)

[email protected]:/home/debian# i=7 
[email protected]:/home/debian# seq --format="file '/home/debian/%G.flv'" $i > myFile.txt 

如何與操作系統包裝在蟒蛇。系統?

>>> 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 

狀態2: 變量是蟒蛇,現在我想調用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") 
+0

'使用os.system( 「seq --format = \」file'/home/debian/%G.flv'\「5> myFile.txt」)'? – Torxed 2013-02-11 10:01:37

回答

3

報價「用反斜槓

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

這是錯的,請運行你在這裏寫的代碼 – 2013-02-11 10:41:03

+0

謝謝KillKill,現在更正了 – Vorsprung 2013-02-11 16:50:42

3

使用三聯報價

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

希望這給是你在找什麼

[[email protected] ~]# 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() 
[[email protected] ~]# 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' 
[[email protected] ~]# 
相關問題