w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python thread timer, not executing or executing instantly
You lost all the indentation in your code snippet, so it's hard to be sure what you did. The most obvious problem is responseTimer.start. That merely retrieves the start method of your responseTimer object. You need to call that method to start the timer; i.e., do responseTimer.start(). Then it will produce the output you expected, with a delay of about 2 seconds before the final "timeout!" is printed.

Categories : Python

working in python console while executing a boost::python module
You have two options: start python with the -i flag, that will cause to drop it to the interactive interperter instead of exiting from the main thread start an interactive session manually: import code code.interact() The second option is particularily useful if you want to run the interactive session in it's own thread, as some libraries (like PyQt/PySide) don't like it when they arn't started from the main thread: from code import interact from threading import Thread Thread(target=interact, kwargs={'local': globals()}).start() ... # start some mainloop which will block the main thread Passing local=globals() to interact is necessary so that you have access to the scope of the module, otherwise the interpreter session would only have access to the content of the thread's scope.

Categories : Python

Alternative for inheritance in python
class A(object): name = 'foo' def get_name(self): # the common function return self.name class B(A): pass In this case B would inherit from A

Categories : Python

is there any alternative to python libtorrent?
Just search on the Python Package Index: https://pypi.python.org/pypi?%3aaction=search&term=torrent&submit=search, and find what suites your need.

Categories : Python

Json alternative for python v2.4
You can take advantage of the str function to turn a dictionary into a string, which will follow a pattern almost identical to JSON. You can recursively save the properties of the object as a dictionary with the property names as keys for their values. The way to load this object would be slightly more difficult, using regular expressions or something to parse the JSON into key-value pairs. For the issues with that, see here.

Categories : Json

Alternative python package repositories
If you're asking for PyPI mirrors, there's an up-to-date list at http://www.pypi-mirrors.org. The primary mirrors are under python.org, but there are some under other domains. As of 7 Aug 2013 (in case you can't reach the mirrors site either) they are: pypi.crate.io pypi.douban.com pypi.hustunique.com From your edit, you ask: Can I mirror PyPI myself? Yes, you can. As the main mirrors page says: Use the bandersnatch mirroring client to set up your own mirror.

Categories : Python

Alternative with less indentation for nested loops in Python
Assuming that (as in your example) the loops are all independent of the parent loops, You want itertools.product(). import itertools for i, j, k, l, m, n, o, p, q in itertools.product(xrange(1, 5), repeat=9): ... Here I use the repeat keyword argument as shorthand, as in your example, the iterables were all the same, but you can also pass it multiple iterables if your iterables are not all the same. It will also be more efficient than many nested loops. Do note that there is likely a better solution to your problem - as iterating with so many nested loops is likely to be a huge amount of iteration, and therefore very slow. Alternatively, if your loops rely on their parent loops or the like (and as such product() isn't suitable), you can define functions to take some of the heavy

Categories : Python

Alternative of "extractall()" of tarfile module in python version 2.4
The tarfile module is present in Python 2.4: http://docs.python.org/release/2.4/lib/module-tarfile.html Quoting from the module documentation: New in version 2.3. It is a pure-python module, so it has no C library dependencies that might prevent it from being installed. The TarFile.extractall() function is easily backported: import copy import operator import os.path from tarfile import ExtractError def extractall(tfile, path=".", members=None): directories = [] if members is None: members = tfile for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 0700 tfile.extract(tarinfo, path) # Rev

Categories : Python

faster or batch alternative to python's socket.gethostbyaddr()?
You can use dnspython module [1], look from_address function. Note: It's thread safe. [1] http://www.dnspython.org/

Categories : Python

Alternative way to extract lines from text (python-regex)
Firstly, I'm pretty sure that you mean data = open('database.txt').readlines() rather than read(). Otherwise, data will be a string rather than a list of lines, and your for line in data won't make any sense. At this point, you're really looking for an indexing solution by keyword, and naive search will stop being efficient enough to give you a timely result. There's really not another approach that's significantly more efficient or less complex. You're going to have to grind your teeth and accept the cost of looking through the entire database. Also, your database can't be all that big if it completely fits in memory :) That said, there are other ways you could do it that will probably be more efficient: Put your keywords in a set, then tokenise the input data into word and look a

Categories : Python

Alternative to Python subprocess module in Google App Engine
GAE only runs python code. Subprocess won't help you. You can't run bash scripts in GAE. You'll have to rewrite the bash script as a python program, at which point you probably just want to import and run your python script.

Categories : Google App Engine

Executing an Excel macro from Python
I've never done this with EnsureDispatch, but here's how you do it with Dispatch from win32com.client import Dispatch xlApp = Dispatch('Excel.Application') result = xlApp.Run("<macro name here>",<the macro variables go here -seperate each one with a comma>) # for example: #result = xlApp.Run("myMacro", "foo","bar") #and make sure you close the xl xlApp.Quit() oh and I'm aslo on python 2.7, (but I doubt it will matter as the dependency is win32)

Categories : Python

Executing a set of codes when python GUI is clicked
Use the command option of a Button: from Tkinter import Tk, Button root = Tk() def func(): '''Place code to convert files in here''' print "Button has been pushed" Button(text="Push me", command=func).grid() root.mainloop() func will only run when the button is pressed.

Categories : Python

Executing shell command from python
You can call a subprocess as if you were in the shell by using Popen() with the argument shell=True: subprocess.Popen("nohup ./op.o > myout.txt &", shell=True)

Categories : Python

Executing a python file from PHP - Linux
This is most likely a permission issue. Try echo exec("whoami"); This will let you know who php is running as. Then you need to verify this user can run the python script. If the file was not created by the same daemon that runs python, you will most likely be denied permission. Update This will let you know who owns all the files you are working with. The file being written to needs to be writable by the user that is running python. If you are running python from ssh, that is most likely not the same user as when you run python from exec. echo exec('whoami') . "<br>"; echo exec("ls -l test.txt") . "<br>"; echo exec("ls -l somefile.py") . "<br>"; Update 2 Because I constantly forget this exists. passthru('python somefile.py 1 2>&1'); This will e

Categories : PHP

Python script executing SQL on Synology NAS
you can install a mysql connector from official mysql source : http://dev.mysql.com/doc/connector-python/en/index.html. bye

Categories : Python

executing perl script from python
Your Perl script is wrong: You read the path from STDIN, not from the command line arguments. You do not remove the newline after reading a line. You would be looking for "foo " instead of "foo". You have no error checking whatsoever. You do not load the Data::Dumper module. And are you sure that you really want to execute the file at $path as Perl code? Cleaned up, I'd write the Perl script as perl -MData::Dumper -do $ARGV[0];' -e'print Dumper \%some_global' input-file.pl >output Or as use strict; use warnings; use Data::Dumper do $ARGV[0]; open my $fh, ">", "output" or die "Can't open output: $!"; print { $fh } Dumper \%some_global; If you really want the filename from STDIN: use strict; use warnings; use Data::Dumper; chomp(my $path = <STDIN>); do $p

Categories : Python

Executing Tkinter Code Successfully (Python 2.7)
It appears that you have some indentation issues. Python isn't free form, so you need to pay attention to indentation: from Tkinter import * class App(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): self.entryLabel = Label(self, text="Please enter a list of numbers (no commas):") self.entryLabel.grid(row=0, column=0, columnspan=2) self.listEntry = Entry(self) self.listEntry.grid(row=0, column=2, sticky=E) self.entryLabel = Label(self, text="Please enter an index value:") self.entryLabel.grid(row=1, column=0, columnspan=2, sticky=E) self.indexEntry = Entry(self) self.indexEntry.grid(row=1, column=2) self.

Categories : Python

import module without executing whole script python
If the problem is arising from executing the LogInPage during the import... you can protect the code in LogInPage. Keep those codes in if __name__ == '__main__: block from being executed by import statements.

Categories : Python

Python - When executing program via CMD, it just closes after the second input
This has to do with how Windows handles the execution. The default is to close right away after the program has terminated. There may be a setting to fix this, but a quick solution is to open up Command Prompt, cd to the direction, and execute your script directly.

Categories : Python

Executing Fabric python code on windows 7
Fabric requires Python version 2.5 or 2.6. Fabric has not yet been tested on Python 3.x and is thus likely to be incompatible with that line of development. It's not so simple to install Fabric on Windows, because it uses some specific C libs that needs to be compiled. Try next in Windows: pip install fabric # Failed! easy_install fabric # Failed again! But if you don't want to install Visual Studio or Cygwin and compile the C code so I will consider another way, more simple. As I have figured out, Fabric needs next Python libs to be installed on Windows: PyCrypto PyWin32 Both requires compilation OR may be installed from the pre-built binary packages (my choice!): PyCrypto: click here PyWin32: click here Download and install these two and you will be finally able to do: pip inst

Categories : Windows

Python Print Output Executing Out of Order
You're not closing the file when you do this: file.close You're just referencing the close method as a value. What you wanted was to call the close method: file.close() Eventually, the file gets garbage-collected, at which point all of its buffered data gets flushed. But meanwhile, you've opened the same file elsewhere and appended new data to it. On many platforms, your left-over buffers would end up overwriting the later-appended data, instead of getting added after them, making this even harder to debug. You got lucky here. :) If you ran this code through a linter, it would have warned you. With pylint, I get "W0104: Statement seems to have no effect". However, note that it can't possibly catch all such errors. For example: import random r = random.random Here, you're setti

Categories : Python

Alternative IDE supporting debugging for Google App Engine in Python (Eclipse + PyDev no debug support on SDK 1.7.6+)
I posted this in google groups a while back. I can run debugging in Boa Constructor using remote debugging. https://groups.google.com/forum/#!topicsearchin/google-appengine/Boa/google-appengine/-m00Qz4Vc7U I am pretty sure it would be trivial to make winpdb work with remote debugging as well, though I haven't tried it (I don't use winpdb ;-) If any other debug environments support similiar remote debugging facilities it shouldn't be too hard to get them going. There a screen shot of Boa debugging in action here https://groups.google.com/forum/#!searchin/google-appengine/debugging$20Boa/google-appengine/ZHHkwr3ok8c/btDno8oPYyAJ T

Categories : Python

Emacs Org Mode: Executing simple python code
There are two ways of getting the result of a source block - output and value. You mixed them up, hence the troubles. First block is fine. To fix the second block: #+begin_src python :results value return 1+1 #+end_src To fix the third block: #+begin_src python :results output print 1+1 #+end_src When output mode is value you must return. Just putting it there like you did with 1+1 won't do. In the third one you want the result to be printed output, but your default session setting is value(mine defaults to output btw). And this bit about org-confirm-babel-evaluate is kind of irrelevant to the question. I just have it set to nil.

Categories : Python

Dynamically reading in a python file and executing it safely
You can consider following method class _DynamicModule(object): def __init__(self, name): self._name = name def load(self, code): execdict = {'__builtins__': __builtins__} exec compile(code, '<string>', 'exec') in execdict for key in execdict: if not key.startswith('_'): if not isinstance(execdict[key], str): execdict[key].__module__ = self._name setattr(self, key, execdict[key]) return self import sys sys.modules['dummy_modules'] = _DynamicModule('dummy_modules').load('print ("!")') This still has pretty big security concerns.

Categories : Python

Executing multiple .py python scripts in same directory in terminal?
Assuming bash: for i in x y z; do python ~/abc/$i.py & done This loop iterates over the strings "x", "y" and "z". each iteration the variable $i is another one of them. So in the first iteration, $i is x, so ~/abc/$i.py is ~/abc/x.py. The second iteration is the same, only with y, and in the third $i is x. So bash actually do python ~/abc/x.py & python ~/abc/y.py & python ~/abc/z.py & Which is what you asked for. The & makes it run in the background. You can do this for any command you invoke.

Categories : Python

Executing shell program in Python without printing to screen
If subprocess.check_ouput is not working for you, use a Popen object and a PIPE to capture the program's output in Python. prog = subprocess.Popen('./myprog', shell=True, stdout=subprocess.PIPE) output = prog.communicate()[0] the .communicate() method will wait for a program to finish execution and then return a tuple of (stdout, stderr) which is why you'll want to take the [0] of that. If you also want to capture stderr then add stderr=subprocess.PIPE to the creation of the Popen object. If you wish to capture the output of prog while it is running instead of waiting for it to finish, you can call line = prog.stdout.readline() to read one line at a time. Note that this will hang if there are no lines available until there is one.

Categories : Python

Getting brackets while executing query into mysql database using python
The result returned by cursor.fetchall() is a tuple of tuples containing the fetched data. Each tuple represents a fetched row. Because you are printing a tuple of tuples, you are seeing the braces. In order to display the data in a prefered format you'll have to iterate over the result and print each row accordingly. The example below would print each row on a new line, and will separate the columns with a vertical bar: for row in result: print " | ".join(row)

Categories : Python

capturing keyboard interrupts during while executing Python scripts
I assume that the problem is that Python parent process receives SIGINT from Ctrl+C and quits with unhandled exception, but the child ignores signal and keeps running. That is the only scenario I was able to reproduce. Actual problem may differ. Catching exception and killing subprocess explicitly with SIGKILL may work. Instead of subprocess.call: proc = subprocess.Popen(['/bin/bash', scriptfile.name]) try: proc.wait() except: proc.kill() raise

Categories : Python

How can I find the currently executing script file and path in python?
In case __file__ is not set, you can get the directory via import sys, os script = os.path.abspath(sys.argv[0] or 'unknown script') directory = os.path.dirname(script))

Categories : PHP

Launch Python debugger while simultaneously executing module as script
After experimenting with this for quite some time, it turns out that this approach actually works: python -c "import runpy; import pdb; pdb.runcall(runpy.run_module, 'somepackage.somemodule', run_name='__main__')" For some reason, the use of pdb.runcall over pdb.run is important.

Categories : Python

Is there a simple method for executing command line statements, in windows, from within python?
Something like this? from subprocess import call call('mysqldump --result-file="db_dump 2013-08-05.sql" --all-databases', shell=True) Just remember, shell=True can be a security risk if you work with untrusted user supplied parameters. E.g. when you let an untrusted use specify the file name.

Categories : Python

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' in executing python script
I see you've cranked out a lot of code, however, it's littered with syntax errors. I'd recommend you try writing smaller chunks at a time, getting each step working as you plug along. First, your while loop is infinte. Second, if you want to use parenthesis with print (which I recommend), for Python 2.x, use this at the top of your files: from future import print_function Third, you should always use os.path for portable filesystem path manipulations. What your error means is that, somewhere, you're trying to add a None type with a string. That's not possible, of course, so Python throws an exception. What you need to do, is to figure out why whatever you're adding is None, and fix that ;) Hope that helps!

Categories : Python

Error in executing python file to configure WAS Admin Console properties
You do not have the environment variable BASE_DIR set. If you use bash, do export BASE_DIR=/path/to/whatever before you run the python code (in the same terminal window) You should also assume sane defaults if BASE_DIR is not defined by user sys.path.append(os.environ.get("BASE_DIR","/some/default/path"))

Categories : Python

Relative paths break when executing Python script from Windows batch?
Yes, that is logical. The files are relative to your working directory. You change that by running the script from a different directory. What you could do is take the directory of the script you are running at run time and build from that. import os def read_file(filename): #get the directory of the current running script. "__file__" is its full path path, fl = os.path.split(os.path.realpath(__file__)) #use path to create the fully classified path to your data full_path = os.path.join(path, filename) with open(full_path, "r") as file: #etc

Categories : Python

jquery code not executing from script, but executing from dev panel
The click handler you've shown is bound to any ".maintypedata img" elements that exist when that code runs. But, the img elements in question are appended to the document dynamically after the "Bamboo" option is clicked. So you need to either run that .click() code after the elements are appended (which is what you were doing by running it from the console) or change it to work as a delegated event handler: $(".maintypedata").on("click", "img", function() { console.log("test"); if(open == false) { var src = $(this).attr("src"); $(".popup").html("<img src='"+src+"'/>"); open = true; $(this).addClass("selected"); $(".popup").slideFadeToggle(function() { });

Categories : Javascript

Executing MDX query in SQL server takes 2 second but executing it via ADOMD and retriving data takes 5 minutes
ADOMD ExecuteCellSet is a very expensive method. In my case I was accessing item.Members[0].Parent which was taking long time as system use to hit DB again and it use to retrieve parent info from the cube. ExecuteCellSet is great if you need some additional info from the cube. I resolved the issue by using ExecuteReader(). Below is the code List<TreeNode> treeNodeList = new List<TreeNode>(); var connection = new AdomdConnection(connString); var command = new AdomdCommand(query, connection); try { connection.Open(); var result = command.ExecuteReader(); TreeNode node = null; int count = 0; while (result.Read()) {

Categories : Dotnet

Executing oracle spool command which is written as a .sql file(eg:spool.sql) from c# just like executing any oracle query using OracleCommand
You can try something like this: string myCommand = PSQLCommand; //This would be the location of your file string myArguments = "PSQLArugments"; Process.Start(myCommand, myArguments); So your command would look like psql.exe i "Path of createfeed.sql" myCommand would = psql.exe (the full path to your executable) myArguments = @"i pathToCreateFeed.sql"

Categories : C#

Alternative for sed ... <(cmd) and cmd | sed
If you're careful with quoting, you can do it like this: option = bash -c 'cmd "$1" "$2" | sed "s/x/y/"' sub The word "sub" at the end is arbitrary but necessary; it's there because $1 in the subshell created with bash -c is actually the second positional argument, not the first one.

Categories : Bash

ORG alternative for C++
No it's not possible to do in any C compiler that I know of. You can however create your own linker script that places the code/data/bss segments at specific addresses.

Categories : C++



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