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)

0 0
原创粉丝点击