我有一個python(v2.7)腳本,需要在寫入檔案之前清除檔案的內容(如果存在)。我可以在命令列上毫無問題地執行“相同”命令,但是python當bash從python. 不知道我錯過了什么。
終極問題:如何使用來自 Python(v2.7)的系統呼叫創建一個空檔案(或清除,如果它存在)?
Bash(成功創建空檔案或清除現有檔案)
$ > test.txt
$ ls -l test.txt
-rw-rw-r-- 1 <owner> <group> 0 Feb 9 11:26 test.txt
Python (w/o `shell=True'; 失敗并出現錯誤)
shell=True我在不使用:的情況下收到以下錯誤OSError: [Errno 2] No such file or directory。另一篇文章建議如果我將所有引數作為單獨的字串引數傳遞,我不應該得到這個錯誤。不知道為什么我會收到這個錯誤。
$ python
>>> import subprocess
>>> subprocess.call(['>', 'test.txt']) # Same result w/ single/double quotes
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 172, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 394, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Python (w/ `shell=True'; 失敗并出現錯誤)
我嘗試shell=True根據其他帖子的建議添加(不應該是安全風險,因為命令是靜態的),但我收到以下bash錯誤:Syntax error: end of file unexpected. 我認為它可能需要一個結尾;(可能是因為如何python呼叫?),所以我嘗試了兩個添加一個;具有相同最終結果的引數。
$ python
>>> import subprocess
>>> subprocess.call(['>', 'test.txt'], shell=True) # Same result w/ single/double quotes
test.txt: 1: test.txt: Syntax error: end of file unexpected
2
>>> import subprocess
>>> subprocess.call(['>', 'test.txt', ';'], shell=True) # Same result w/ single/double quotes
test.txt: 1: test.txt: Syntax error: end of file unexpected
uj5u.com熱心網友回復:
shell=True錯誤
使用它時,給出的命令將被格式化為一個字串
然后將給出的命令字串解釋為原始 shell 命令
正確的用法應該是這樣的:
>>> import subprocess
>>> subprocess.call('> test.txt', shell=True)
0
>>>
# There will now be an empty file called
# 'test.txt' in the same directory
shell=False錯誤
您正在運行的命令應該在shell之上運行,但是當使用這種方式時,它會嘗試通過將其作為 PATH 中的命令呼叫來運行您的字串
但是,我不知道如何為您的案例解決這部分問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425669.html
標籤:Python 重击 python-2.7 Unix
