Run shell command with input redirections from python 2.4?

前端 未结 3 1894
渐次进展
渐次进展 2021-02-13 18:50

What I\'d like to achieve is the launch of the following shell command:

mysql -h hostAddress -u userName -p userPassword 
databaseName < fileName
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 19:12

    The symbol < has this meaning (i. e. reading a file to stdin) only in shell. In Python you should use either of the following:

    1) Read file contents in your process and push it to stdin of the child process:

    fd = open(filename,  'rb')
    try:
        subprocess.call(cmd, stdin=fd)
    finally:
        fd.close()
    

    2) Read file contents via shell (as you mentioned), but redirect stdin of your process accordingly:

    # In file myprocess.py
    subprocess.call(cmd, stdin=subprocess.PIPE)
    
    # In shell command line
    $ python myprocess.py < filename
    

提交回复
热议问题