Running Bash commands in Python

前端 未结 10 1686
礼貌的吻别
礼貌的吻别 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

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

提交回复
热议问题