w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
subprocess's Popen closes stdout/stderr filedescriptors used in another thread when Popen errors
I would like to answer your questions with: Yes. You shouldn't have to. No. The error occurs indeed in Python 2.7.4 as well. I think this is a bug in the library code. If you add a lock in your program and make sure that the two calls to subprocess.Popen are executed atomically, the error does not occur. @@ -1,32 +1,40 @@ import time import threading import subprocess +lock = threading.Lock() + def subprocesscall(): + lock.acquire() p = subprocess.Popen( ['ls', '-l'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) + lock.release() time.sleep(2) # simulate the Popen call takes some time to complete. out, err = p.communicate() print 'succeeding command in thread:', threading.current_t

Categories : Python

subprocess.Popen - `cwd` is not honored
If you are just trying to change the current working directory, you could use: os.chdir('c:\test') Note the double backslash as the backslash is a special character in Python that needs to be escaped. Also, to check your current working directory, you can use: os.getcwd()

Categories : Python

subprocess.popen (python) in C
In C, you get the maximum number of options by first calling fork() to create a new process (the eventual subprocess), then one of the exec*() family of functions to execute the subprocess. Both the original process and the new process will run concurrently, so you can exchange (read and/or write data) via pipes or socket pairs. Finally, use e.g. waitpid() in a loop to wait for the new process to exit, and "reap" its exit status. For example: #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> int main(void) { pid_t child, p; int status; /* * Prepare pipes et cetera first. */ /* Fork to create the subprocess. */ child = fork(); if (child == (pid_t)-1) { /* Cannot fork(); usually out of re

Categories : Python

subprocess.Popen and shell interpretation
You want to use shlex.split to split command: subprocess.Popen(shlex.split(command),stdout=subprocess.PIPE) The problem is that str.split doesn't care if you've tried to put something in quotes -- It will split the string on whitespace no matter how much you quote things. e.g. >>> "foo 'bar baz'".split() ['foo', "'bar", "baz'"] >>> import shlex >>> shlex.split("foo 'bar baz'") ['foo', 'bar baz']

Categories : Python

subprocess.Popen() launches two process instead of one
You are using squeezelite's -z option, which daemonizes the process. This explains why an additional process is being created. I think the best solution is to use the OS daemonizing tools (eg. start-stop-daemon), simplifying the calls you do with Python. There is a guide about daemonizing squeezelite in Debian squeeze, which can help get you started. You need to start the process and save its PID in a file, so you can stop it later. One approach might be to use a daemon script that takes two parameters: start/stop and an identifier for your button.

Categories : Python

subprocess.Popen can't find file?
I set an environment variable EM_SAVE_DIR=1 as recommended on the github page.... Though it was recommended for debugging purposes, the fact of the matter is that it caused the files to remain both in memory and in the correct location, such that the error now only gets thrown on executables that I mistakenly didn't have anywhere on my PATH (cmake, sh, and make). Though at some point later today, if I get all these tests worked out for runner.py, I may need to ask about making it work on visual studio, which throws error 6 on not finding a correct file in the tmp directory, and seems to be ignoring EM_SAVE_DIR=1....

Categories : Python

How to control gdb using Python subprocess.Popen?
.communicate waits for a Popen object to finish execution. Since you are trying to talk to gdb while it's running, this will just hang forever. gdb isn't going to exit without any input. Additionally you need to write the newlines yourself to emulate the user hitting enter. what you want to do is write into and read from gdb while it is executing. For this, use p1.stdin.write('break main ') (note the ' ') when sending input, and p1.stdout.readline() when reading output. This applies to the break in the beginning, the args you are sending, and the continues. On sending the arguments and beggining executing, you should also be sure to start gdb. p1.stdin.write('start ' + args1 + ' ') p2.stdin.write('start ' + args2 + ' ') You also want to handle the case where one process terminate

Categories : Python

subprocess.Popen: mkvirtualenv not found
Edit: I learned that mkvirtualenv is a shell function. In this case the question becomes how to run shell function in python. My answer below can be applied to standalone binaries. For your question, please look at the answer: http://stackoverflow.com/a/5826523/1906700 You can indirectly call mkvirtualenv() function from the script that defines it. Set PATH variable correctly The problem seems to be caused by your $PATH variable. You need to correctly set this variable so that mkvirtualenv executable can be found. For example, if you have mkvirtualenv executable in `/home/thore/scripts, you need to set your $PATH in .bashrc or .zshrc (depending on your shell) as follows: export PATH=$PATH:/home/thore/scripts In that way, mkvirtualenv script will be found correctly and run. Another

Categories : Python

subprocess.Popen doesn't run the bash command?
I suspect that IDLE redirects Python's stdout so that printing happens in the window, but it doesn't redirect file descriptor 1, so that any subprocess happily prints to that file descriptor. Try to start IDLE from the command line, run these lines and see if their output is printed to the terminal where IDLE is called from. Solutions: Don't use IDLE. Call your stuff from a python interpreter called from the command line. Redirect the output of your processes to a pipe, read this pipe and output it. Such as: sp = subprocess.Popen(['ls'], stdout=subprocess.PIPE) for i in sp.stdout: print i sp.wait()

Categories : Python

Popen send_signal signal not received in subprocess
I'd guess that the SIGINT is being sent to the subprocess before it even has a chance to load up all of Python, so before it installs the SIGINT handler, meaning it will die right away. You probably want to watch the subprocess for some successful-load condition to be met (perhaps just sending a byte on a pipe) before sending it any SIGINT signals that you expect to be handled by your own handler code.

Categories : Python

python - subprocess.Popen() synax errors
The problem is that you're trying to run a shell command without the shell. What happens is that you're passing all of those strings—including "|" and everything after is—as arguments to the echo command. Just add shell=True to your call to fix that. However, you almost definitely want to pass the command line as a string, instead of trying to guess at the list that will be joined back up into the string to pass to the shell. Or, even better, don't use the shell, and instead pipe within Python. The docs have a nice section about Replacing shell pipeline (and all kinds of other things) with subprocess code. But in your case, the thing you're trying to pipe is just echo, which is quite silly, since you already have exactly what echo would return, and can just feed it as the input to

Categories : Python

Inconsistent stdout on Python subprocess.popen
I suppose it is the """stuff (which would look nicer as '"', BTW). You are calling Popen() without shell=True, so you should give the parameters as you want them. On a normal egrep call the "" are stripped away by the shell, a step which you don't have here. SO you don't need them here.

Categories : Python

Formatting text from a subprocess.Popen command
It looks like you need to iterate through all the values in snap.split(' '): snap, err = epoch.communicate() print " Epoch Time" for stamp,_,_,_,snaptime,_ in zip(*[iter(snap.split(' '))]*6): print('{} {}'.format(stamp, snaptime)) The above uses the zip(*[iter(s)]*n) grouper idiom to cluster the data into n-length groups.

Categories : Python

How can i parse strings as the inputs to subprocess.Popen?
You haven't said how your code fails, but it looks like you are trying to give MEncoder binary strings as command line parameters. http://www.mplayerhq.hu/DOCS/HTML/en/menc-feat-selecting-input.html says that you can give the filename in the command line, not the contents of a file. so to answer your question: with open('merged.flv', 'wb') as f: f.write(out1 + out2) ffmpeg_command2 = ["mencoder", "your", "other", "args", "merged.flv"]

Categories : Python

execute cat command in subprocess,Popen() of python
The problem is that you're passing the command as multiple args. You need to pass them as a list or a tuple. Like: subp.Popen([ 'egrep','list_of_IDs','/home/bimlesh/python/result.log' ], stdout=subp.PIPE,stderr=subp.PIPE,shell=True)

Categories : Python

Subprocess freezes popen().stdout.read
Use communicate() instead: import subprocess process = subprocess.Popen(['app'], shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE) out, err = process.communicate("Some String") print out Also, make sure you end your C++ process at some point. For example, when you reach the end of your input stream: #include <string> #include <iostream> using namespace std; int main(int argc, char** argv) { //...Prep work... while (cin) { // <-- Will eventually reach the end of the input stream string input; cin >> input; //...Some Work ... string response = input; cout << response; } } There is a warning for this in python's documentation: http://docs.pytho

Categories : C++

Why does subprocess.Popen block the response of SimpleHTTPServer.SimpleHTTPRequestHandler
Ok, so after Nikhil referred me to this question http://stackoverflow.com/questions/3973789/... I figured out that I need self.send_response(200), self.send_header("Content-Length", str(len(uuid_gen))) and self.end_headers(). This means the working code looks like this: #!/usr/bin/env python import SimpleHTTPServer import SocketServer import subprocess import uuid class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_POST(self): print 'in do_POST' uuid_gen = str(uuid.uuid1()) subprocess.Popen(['python', 'sleep.py']) print 'subprocess spawned' self.send_response(200) self.send_header("Content-Length", str(len(uuid_gen))) self.end_headers() self.wfile.write(uuid_gen) Handler = MyRequestHandler server

Categories : Python

python subprocess.popen tshark works with some args, but not others
subprocess.Popen by default bypasses CMD.EXE / sh, therefore command line I/O redirections (<, >) will not work. You can get a similar effect like this: tsharkCall = ["tshark", "-i", "-", "-V"] tsharkIn = open("tshark.pcap", "rb") tsharkOut = open("tshark.txt", "wb") tsharkProc = subprocess.Popen(tsharkCall, stdin=tsharkIn, stdout=tsharkOut, executable="C:\Program Files\Wireshark\tshark.exe")

Categories : Python

Ensuring order of execution for subprocess.Popen calls
It looks like you want subprocess.check_call() instead of Popen. From the docs: Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. Your build function would look something like: def build_package(package, config): command = '; '.join(config[package]['build']) subprocess.check_call(command, shell=True) If you're actually using the Popen object, you can call the wait() method to wait for the subcommand to finish: def build_package(package, config): command = '; '.join(config[package]['build']) build = subprocess.Popen(command, shell=True) # do something with the build object build.wait() # command is done

Categories : Python

Subprocess.Popen: cloning stdout and stderr both to terminal and variables
You could spawn threads to read the stdout and stderr pipes, write to a common queue, and append to lists. Then use a third thread to print items from the queue. import time import Queue import sys import threading import subprocess PIPE = subprocess.PIPE def read_output(pipe, funcs): for line in iter(pipe.readline, ''): for func in funcs: func(line) # time.sleep(1) pipe.close() def write_output(get): for line in iter(get, None): sys.stdout.write(line) process = subprocess.Popen( ['random_print.py'], stdout=PIPE, stderr=PIPE, close_fds=True, bufsize=1) q = Queue.Queue() out, err = [], [] tout = threading.Thread( target=read_output, args=(process.stdout, [q.put, out.append])) terr = threading.Thread( target=read_output, ar

Categories : Python

Using subprocess.popen with multiple stdin to configure system : Python 2.7
I haven't used Postgres in ages, but I'm guessing you want to su to postgres, and then run a command that requires postgres' rights. But your run(['sudo', 'su', '-', 'postgres']) will probably just open a shell and wait; run(['createuser'], False, 'testuser') will likely never get run. Instead, I believe you should combine these two commands. See the "-c" option to su. Alternatively, and a little more securely, you could give your source user postgres rights in sudo, to take root out of the equation and make your code a little simpler.

Categories : Python

How to send an argument from one python script to another using subprocess.Popen communicate?
When you do: process.communicate(f) you are writing to the standard input of process; the problem is that the latter program must read the data from its input stream in order to make use of it. You could change file2.py to something like: import sys def c(x): print x for f in sys.stdin: c(f) You seem to be thinking that communicate() allows the parent and child processes to share variable bindings; that's not the case. As written in your question, file2.py would generate an error to the effect that name 'f' is not defined.

Categories : Python

terminate a process and its subprocesses started with subprocess.popen the right way (windows and linux)
Like Henri Korhonen mentioned in a comment, grouping processes should help. Additionally, if you are on Windows and this is Cygwin Python that starts Windows applications, it appears Cygwin Python can not kill the children. For those cases you would need to run TASKKILL. TASKKILL also takes a group parameter.

Categories : Python

How to pass utf8 strings properly from python to hunspell via subprocess.Popen?
As Iwan Aucamp suggested in the comments, the solution is to use: hunspell -i UTF-8 ... i.e. make sure that hunspell knows it's getting UTF-8 strings. Once I added that to my code, the results I was getting in the shell (even without the -i flag) and the results I was getting by piping strings to hunspell from Python were the same.

Categories : Python

'cleartool find -print' inside Python3 'subprocess.check_output' returns empty string
As I mention in "cleartool find" prerequisite, a find must be executed from within a ClearCase view (snapshot or dynamic); You need to make sure the Python subprocess: keep the current path has the vob mounted in that process (if you are using a dynamic view). torek mentions in the comments a simpler cause for the issue: The default for the various subprocess invocations is shell=False See his answer. That is especially true if your path (on the shell) is /vobs: that is only valid for a view which has been set, which spawns its own process. See "Python and ClearCase setview" for more. It wouldn't allow an alias like 'clt' to work either ('cleartool' might work, 'clt' not: see "Clearcase running commands from a script (error: Bad phone number)" as an example) Try it in a dyna

Categories : Python

Closing socket after subprocess.Popen leaves socket in TIME_WAIT as long as child process is still running
Closing socket after subprocess.Popen leaves socket in TIME_WAIT as long as child process is still running No it doesn't. It leaves it in TIME_WAIT for a fixed amount of time, 2 or 4 minutes. After the close it has nothing to do with the child process at all.

Categories : Python

Is it necessary to call Popen.wait() to "clean up" after the Popen object?
No, you don't have to call wait if you are calling poll. They basically do the same thing, except that wait waits infinitely. poll: if self.returncode is None: if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: self.returncode = _GetExitCodeProcess(self._handle) return self.returncode wait: if self.returncode is None: _subprocess.WaitForSingleObject(self._handle, _subprocess.INFINITE) self.returncode = _subprocess.GetExitCodeProcess(self._handle) return self.returncode This is the code for windows implementation of the subprocess module, but all other should follow the same rules. On MacOS X and I assume the implementation for Linux is the same, they both call os.waitpid.

Categories : Python

Why does contains() method find empty string in non-empty string in Java
An empty string occurs in every string. Specifically, a contiguous subset of the string must match the empty string. Any empty subset is contiguous and any string has an empty string as such a subset. Returns true if and only if this string contains the specified sequence of char values. An empty set of char values exists in any string, at the beginning, end, and between characters. Out of anything, you can extract nothing. From a physical piece of string/yarn I can say that a zero-length portion exists within it. If contains returns true there is a possible substring( invocation to get the string to find. "aaa".substring(1,1) should return "", but don't quote me on that as I don't have an IDE at the moment.

Categories : Java

Returning a Unicode string vs. Returning a normal string encoded as UTF-8?
UTF-8 is an encoding of the entire Unicode character set. It is backwards compatible with ASCII. For characters outside the ASCII set, multibyte encodings are used. All ASCII strings are Unicode strings. All Unicode strings are not ASCII strings.

Categories : Python

Timeout within a popen works, but popen inside a timeout doesn't?
In the first block, the timeout is raised in the child, killing it and returning control to the parent. In the second block, the timeout is raised in the parent. The child never gets the signal. See io.c https://github.com/ruby/ruby/blob/trunk/io.c#L6021 and timeout.rb https://github.com/ruby/ruby/blob/trunk/lib/timeout.rb#L51

Categories : Ruby

PHP empty($string) return true but string is not empty
If you're using magic getter within your class, the docs page documents a rather tricky behaviour: <?php class Registry { protected $_items = array(); public function __set($key, $value) { $this->_items[$key] = $value; } public function __get($key) { if (isset($this->_items[$key])) { return $this->_items[$key]; } else { return null; } } } $registry = new Registry(); $registry->empty = ''; $registry->notEmpty = 'not empty'; var_dump(empty($registry->notExisting)); // true, so far so good var_dump(empty($registry->empty)); // true, so far so good var_dump(empty($registry->notEmpty)); // true, .. say what? $tmp = $registry->notEmpty; var_dump(empty($tmp)); // false as expected

Categories : PHP

Force JAXB to Interpret Empty Element as Null not Empty String
Since this is just for one element, below is one way you could get this to work with any JAXB implementation. Java Model Foo Setup your class to use field access by leveraging the @XmlAccessorType annotation. Then initialize the field corresponding to the element as "". The implement the get/set methods to treat "" as null. import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Foo { private String bar = ""; public String getBar() { if(bar.length() == 0) { return null; } else { return bar; } } public void setBar(String bar) { if(null == bar) { this.bar = ""; } else { this.bar = bar; } } } Demo Code Below is some de

Categories : Java

Why is a empty variable declaration of type String "null" and not "" (blank or empty)
It's not "null", it's null. But println displays it like that because it's defined to do so (see the Javadocs). As for why it's not initialized to an empty string, that's because String is a class type, and the default value for references to class instances is always null. There is a big difference between no object at all (i.e. null) and an object in an "empty" state.

Categories : Java

GetContent() empty string and empty inputstream for "text/html"
Use the JavaMail demo program msgshow.java (download here) to read your test message file to make sure the file format is correct. (Copy/paste isn't the most reliable way to create a properly formatted file.) "java msgshow -m The JavaMail FAQ has additional debugging tips.

Categories : Java

Is it better to make a method for returning a string from an Enum? or to have an extra string variable to hold the string value?
Your getSize() method can be reduced to: public string getSize() { return pSize.ToString(); } Given that the method is really this simple, it seems rather pointless to provide this as a separate method. If you simply expose pSize as a property (or read-only property) the user can simply call ToString() on that property: public EnumSize Size { get { return this.pSize; } }

Categories : C#

Mysql returning empty set
dont use single quotes around table database , columns name use instead backticks . try this: from `db`.`table1` al, `db`.`table2` ald, `db`.`table3` ag, `db`.`table4` aa, `db`.`table5` aa1, `db`.`table6` et, `db`.`table7` u try this with joins select ag.name, aa.name, al.object_id, u.name, al.performed_by, al.datetime, aa1.name, et.name, ald.name, ald.value from `db`.`table1` al Inner join `db`.`table2` ald On al.id = ald.log_id Inner join `db`.`table3` ag On al.group_id = ag.id Inner join `db`.`table4` aa On """""the condition of relation with this table"""" Inner join `db`.`table5` aa1 On al.action_id = aa1.id Inner join `db`.`table6` et On ald.type_id = et.id Inner join `db`.`table7` u On al.object_id = u.user_id where al.datetime > DATE_SUB(sysda

Categories : Mysql

Why is xlsread returning empty?
xlsread only returns numeric data when only one output is specified. If the .xlsx file contains only text data, it will return empty. To remedy this, specify the outputs: [fileName,dirName]=uigetfile('.xlsx'); [~,~,rawData] = xlsread(fullfile(dirName,fileName)); will return the entire contents of the sheet without MATLAB parsing the results and deciding what's text and what's numeric data.

Categories : Excel

php exec() returning empty value
exec will be empty if it can not find the command you are trying to run. You need to tell php where it can find mogrify by using putenv. In my case mogrify's path is /opt/local/bin. So the following code would work, you will just need use the correct path for your environment. putenv("PATH=/opt/local/bin"); exec('mogrify -auto-orient -verbose -format jpg '.$dir."/".$user_file_name,$ouput); fb($output); curl_exec('mogrify -auto-orient -verbose -format jpg '.$dir."/".$user_file_name,$output); fb($output); $output = shell_exec('mogrify -auto-orient -verbose -format jpg '.$dir."/".$user_file_name); fb($output); I hope that helps.

Categories : PHP

TextField is returning nil when it is empty
It is a formal change from iOS6 to iOS7. The text field used to return an empty string, but now you have a nil string instead. @property (weak, nonatomic) IBOutlet UITextField *tf; // iOS6 if (![self.tf.text isEqualToString:@""]){ // iOS7 if (self.tf.text != nil && ![self.tf.text isEqualToString:@""]) {

Categories : IOS

unwanted returning empty object
Update based on further clarifications from comments below $(document).ready(function () { /***The objects that I am creating with arrays***/ var columnOne = { '$100':'On the world political map, where were some of the major states and empires located about 1500 A.D. (C.E.)?', '$200':'What were the artistic, literary, and intellectual ideas of the Renaissance?', '$300':'Where were the five world religions located around 1500 A.D. (C.E.)?', '$400':'What were the regional trading patterns about 1500 A.D. (C.E.)?', '$500':'Why were the regional trading patterns important?' }; var columnTwo = { '$100':'A', '$200':'B', '$300':'C', '$400':'D', '$500':'E' }; var columnThree = { '

Categories : Jquery



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.