Domanda

Why does this work:

diff = subprocess.Popen(['cat','foo.txt'], stdout=subprocess.PIPE)
pr = subprocess.Popen(sublime, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, stdin=diff.stdout)
pr.wait()
if pr.returncode == 0:
    msg = pr.stdout.read()
    print "message : %s" % msg
    er = pr.stderr.read()
    print er

But this doesn't:

diff = subprocess.Popen('open("foo.txt","r")', stdout=subprocess.PIPE)

I am trying to launch sublime from command line terminal and pass the text entered in sublime to a variable.

What bothers me I can achieve with the first one but it will not work on windows!

È stato utile?

Soluzione

Because cat is a shell command, but open is a Python function. subprocess with shell=True invokes something like bash (and with shell=False, it does roughly what bash also does, but with less extra parsing) - so, basically, it can run any command you can run directly in a terminal without having to open another process (like the Python interpreter) first. You could do something like:

subprocess.POpen(r'python -c "open(\"foo.txt\", \"r\")', stdout=subprocess.PIPE)

but that's a bit ridiculous.

The reason the first code doesn't work on Windows is because Windows has no cat command. But you can do what you're trying to achieve without invoking any other subprocess than sublime - essentially, the equivalent of doing sublime < foo.txt rather than cat foo.txt | sublime.

To do this, read the data from the file into a variable first, then send it to the subprocess using communicate:

sublime = subprocess.POpen(['sublime'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
data = open("foo.txt", 'rb').read()
out, err = sublime.communicate(data)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top