简体   繁体   中英

python3 woes with passing string to stdin of subprocess

How do I make this unix command ... work in python3?

unix command

echo 'alter table in db' | zenity --text-info --width 600 --height 300 --title 'has this sql been done?'

The command above pops up a box with the text and I can then capture the user's response.

In python3 I thought I could just write this to the stdin of a subprocess but I keep getting cryptic errors that I am unable to get round

below is the python program to do this

#!/usr/bin/env python3
import subprocess

cmd = ['zenity', '--text-info', '--width', 600, '--height', 300, '--title', 'has this sql been done?']

pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE,  stderr=subprocess.STDOUT)

data='alter table in db'

resp = pipe.communicate(input=data)[0]

this python script however fails with

Traceback (most recent call last):
    pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE,  stderr=subprocess.STDOUT)
  File "/usr/lib/python3.6/subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.6/subprocess.py", line 1275, in _execute_child
    restore_signals, start_new_session, preexec_fn)
TypeError: expected str, bytes or os.PathLike object, not int

any ideas will be much appreciated

This:

cmd = ['zenity', '--text-info', '--width', 600, '--height', 300, '--title', 'has this sql been done?']

should be this:

cmd = ['zenity', '--text-info', '--width', '600', '--height', '300', '--title', 'has this sql been done?']

even 300 and 600 are meant to be numbers, you still present them as strings in the command line.

!/usr/bin/env python3

import subprocess

cmd = ['zenity', '--text-info', '--width', '600', '--height', '300', '--title', 'has this sql been done?']

pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)

data='alter table in db'

resp = pipe.communicate(input=bytearray(data, 'utf-8'))[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM