Running Bash commands in Python

前端 未结 10 1622
礼貌的吻别
礼貌的吻别 2020-11-21 05:16

On my local machine, I run a python script which contains this line

bashCommand = \"cwm --rdf test.rdf --ntriples > test.nt\"
os.system(bashCommand)


        
相关标签:
10条回答
  • 2020-11-21 05:52

    Also you can use 'os.popen'. Example:

    import os
    
    command = os.popen('ls -al')
    print(command.read())
    print(command.close())
    

    Output:

    total 16
    drwxr-xr-x 2 root root 4096 ago 13 21:53 .
    drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
    -rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
    -rw-r--r-- 1 root root   77 ago 13 21:53 test.py
    
    None
    
    0 讨论(0)
  • 2020-11-21 05:52

    To run the command without a shell, pass the command as a list and implement the redirection in Python using [subprocess]:

    #!/usr/bin/env python
    import subprocess
    
    with open('test.nt', 'wb', 0) as file:
        subprocess.check_call("cwm --rdf test.rdf --ntriples".split(),
                              stdout=file)
    

    Note: no > test.nt at the end. stdout=file implements the redirection.


    To run the command using the shell in Python, pass the command as a string and enable shell=True:

    #!/usr/bin/env python
    import subprocess
    
    subprocess.check_call("cwm --rdf test.rdf --ntriples > test.nt",
                          shell=True)
    

    Here's the shell is responsible for the output redirection (> test.nt is in the command).


    To run a bash command that uses bashisms, specify the bash executable explicitly e.g., to emulate bash process substitution:

    #!/usr/bin/env python
    import subprocess
    
    subprocess.check_call('program <(command) <(another-command)',
                          shell=True, executable='/bin/bash')
    
    0 讨论(0)
  • 2020-11-21 05:56

    subprocess.Popen() is prefered over os.system() as it offers more control and visibility. However, If you find subprocess.Popen() too verbose or complex, peasyshell is a small wrapper I wrote above it, which makes it easy to interact with bash from Python.

    https://github.com/davidohana/peasyshell

    0 讨论(0)
  • 2020-11-21 05:57

    Call it with subprocess

    import subprocess
    subprocess.Popen("cwm --rdf test.rdf --ntriples > test.nt")
    

    The error you are getting seems to be because there is no swap module on the server, you should install swap on the server then run the script again

    0 讨论(0)
提交回复
热议问题