running bash commands in python
来源:互联网 发布:aspen优化 编辑:程序博客网 时间:2024/06/05 22:54
http://stackoverflow.com/questions/4256107/running-bash-commands-in-python
Questiion:
--------------------
On my local machine I run a python script which contains this line
bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"os.system(bashCommand)
This works fine.
Then I run the same code on a server and I get the following error message
'import site' failed; use -v for tracebackTraceback (most recent call last):File "/usr/bin/cwm", line 48, in <module>from swap import diagImportError: No module named swap
So what I did then is I inserted a "print bashCommand" which prints me then the command in the terminal before it runs it with os.system().
Of course I get again the error (caused by os.system(bashCommand)) but before that error it prints the command in the terminal. Then I just copied that output and did a copy paste into the terminal and hit enter and it works...
Does anyone have a clue what's going on :(?
Answer:
------------------------------------------------
Don't use os.system
. Use subprocess.
Like in your case:
bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"import subprocessprocess = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)output = process.communicate()[0]
后记:
--------
也可以考虑
bash_command = "ls *.txt" + " > flist.t"
print "bash_command: %s"%bash_command
#process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)
#output = process.communicate()[0]
output = subprocess.call(bash_command, shell=True)
- running bash commands in python
- Running system commands in Java applications
- Running system commands in Java applications
- [Python] Commands in Django
- Linux Commands for Beginners--Arithmetic in Bash--expr,let commands
- Bash Commands - Special Charactors # ? $
- Bash Commands - $ # Variable Substitution
- Bash Commands - Comparison Operators
- Running and Debugging MEL commands
- Running shell commands from Emacs
- Bash Commands - Using the [[ ... ]] rather than [ ... ] can prevent many logic errors in scripts.
- Bash Commands - tr cat tac
- Bash Commands - chmod # Invoking script
- Bash Commands - # Integer or string?
- Bash Commands - Arithmetic Tests using (( ... ))
- Bash Commands - File test operators
- Learn BASH -- Grouping Commands(from bash manual)
- 高级bash编程一书Example 3-3. Running a loop in the background的问题
- 现在我给你两种选择,一学编程,二不学编程
- weakSelf的宏定义及用法
- matlab实现excel表格到Markdown表格
- jQuery超酷HTML DOM元素纸张3D折叠特效
- 常用数据结构--线性结构
- running bash commands in python
- 第一周项目二 长方体柱类
- 第3周项目4 考了语文数学的学生
- 什么是类的成员函数和非成员函数
- POJ2632 Crashing Robots 模拟题
- Linux驱动中的并发控制
- 改造-TCP-Java-客户机/服务器应用程序-并发-限制线程上限
- 委托、Lambda表达式和事件
- 纪念新的开始