w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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

Executing a script within a script but continuing on error(s) and saving them to file
errors = open('errors.txt', 'w') try: execfile("script.py") except Exception as e: errors.write(e) try: execfile("other.py") except Exception as e: errors.write(e) errors.close()

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

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

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

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

difference between executing script using bash file.sh and ./file.sh
If "file.sh" is not executable then ./file.sh will not work but bash file.sh will. If "file.sh" does not start with the line #!/bin/bash (or another path to a valid bash interpreter) then ./file.sh will not work but bash file.sh will. Basically, in order for a script to look like an executable file it must: Have execute permission. Start with the line #!/path/to/interpreter.

Categories : Bash

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

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

Executing shared library file from php script
After setting the permission execute in following manner will solve the problem: $a=exec('/home/technoworld/Videos/LinSocket/client "critic good"'); No need to give ./client just like I was making mistake! client is the executable file that I wanted to execute and "critic good" is argument to be passed!

Categories : PHP

Using variables in bash script to set ini-file values while executing
Not quite sure whether this helps or not: This calls the program script five times: for n in 1 2 3 4 5 do ./program $n input.ini done Then in program, refer to the first parameter $n as $1. The second parameter input.ini is $2.

Categories : Bash

How to catch signals from a shell script which is executing a file which may throw it?
In part, see Exit status codes greater than — possible? The WIFSIGNALED stuff tells you that a process was signalled, but there's a problem for the shell encoding that, and it does it by encoding a signalled exit status as 128 + signal number (129 for HUP, 130 for INT, etc). To demonstrate shell and signal exit statuses: $ cat killme.sh #!/bin/bash kill ${1:-"-INT"} $$ $ ./killme.sh -HUP; echo $? Hangup: 1 129 $ ./killme.sh -TERM; echo $? Terminated: 15 143 $ ./killme.sh -QUIT; echo $? 0 $ ./killme.sh -PIPE; echo $? 141 $ ulimit -a core file size (blocks, -c) 0 ... $ This more or less justifies my '128+signum' claim (the -QUIT behaviour is unexpected, but explainable after a fashion — it normally dumps core, but didn't because ulimit has them disabled). In bash, you can g

Categories : C

Calling and executing vb script by opening command prompt through Batch file
Here you go ... Set WshShell = wscript.CreateObject("wscript.Shell") WshShell.Run "cmd" WScript.Sleep 100 WshShell.AppActivate "C:Windowssystem32cmd.exe" WScript.Sleep 100 wshshell.sendkeys "vsh" wshshell.sendkeys "{ENTER}" wshshell.sendkeys "2" wshshell.sendkeys "{ENTER}" wshshell.sendkeys "tls display agents > Agentstat.txt" wshshell.sendkeys "{ENTER}" wshshell.sendkeys "PAUSE" wshshell.sendkeys "{ENTER}" wshshell.sendkeys "quit" wshshell.sendkeys "{ENTER}"

Categories : Batch File

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 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

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

Launch a Matlab script based on a file extension
Then you'll need the dir function to list the folder contents and the fileparts function to get the extensions. You can also have a look at this question to see how to get a list of all files in a directory that match a certain mask. So: % get folder contents filelist = dir('/path/to/directory'); % keep only files, subdirectories will be removed filelist = {filelist([filelist.isdir] == 0).name}; % loop through files for i=1:numel(filelist) % call your function, give the full file path as parameter plot_compact_2(fullfile('/path/to/directory', filelist{i})); end

Categories : Matlab

Is there an alternate to transactions that allow executing multiple concurrent queries to a table & making sure the table is in consistent state?
MySQL features table locks and locks (a kind of mutex). PHP supports pretty much all POSIX locking mechanisms, such as mutexes and semaphores (but these are not available by default, see the related "Installing/Configuring" manual chapters). But really, I see little reason why you would want to implement your own synchronisation mechanism: transactions exist for this purpose precisely, and are likely to be more efficient and reliable than anything home-brewed. (if performance is your concern, then a database back-end may not be the right choice)

Categories : PHP

Are you allowed to have an alternate source for a script?
Yes, you can do it. HTML5 Boilerplate has a good example for jQuery loading. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"></script>')</script> But it uses it the other way around. If the script from google couldn't be loaded, it falls back to your local script. You should load the CDN version as a first try anyway, as it loads quicker than a "local" version.

Categories : Javascript

Redirect output of a .bat file run by a python script to GUI, and making that script into EXE
You could use the subprocess module to call your script Example calling the 'ls' command on Linux: >>> from subprocess import call >>> call(['ls', '-l']) total 0 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file1 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file2 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file3 0

Categories : Python

Any cleaner or alternate way to write sql join script
Your query is good, but I think to use Table2 table outside subquery would be better option. SELECT * FROM ( SELECT StudentNumbers, ExamType, MAX(ExamDate) AS ExamDate FROM Table1 GROUP BY StudentNumbers, ExamType ) t1 JOIN Table1 t2 ON t1.StudentNumbers = t2.StudentNumbers AND t1.ExamType = t2.ExamType AND t1.ExamDate = t2.ExamDate WHERE EXISTS( SELECT 1 FROM Table2 t3 WHERE t1.StudentNumbers = t3.StudentNumbers AND t1.ExamType = t3.ExamType )

Categories : SQL

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

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

Run python file within python script, passing arguments
I would try doing somehting like this. os.system("appcfg.py arg1 arg2 arg3") I would look into this portion of the os documentation. Goodluck.

Categories : Python

Executing a PHP script containing a path to another PHP script in another location
The include path only applies if you give a relative pathname. You gave an absolute pathname (starts with "/"), so PHP was looking for the file in /scripts (that is, at the root directory of your computer). You have two options: Use a relative pathname, like "./scripts/checkcmtimg.php" or simply "scripts/checkcmtimg.php". This will involve the include_path, searching each directory in the include path for that relative path. Use an absolute pathname, like "/Users/peter/Documents/firm/worlddiki/na/ejs/scripts/checkcmtimg.php". This will not use the include_path, it will search for the file in just the one location.

Categories : PHP

How to write the results of a batch file called in a Python script to a file
Why are you calling list2cmdline? This doesn't actually call the subprocess. Use subprocess.check_output instead: import os output = [] for _, _, files in os.walk(directory): for f in files: fullpath = os.path.join(directory, os.path.basename(f)) output.append(subprocess.check_output([fullpath])) print ' '.join(output)

Categories : Python

Invoke python script from another python script and set execution directory of the executed script
You could use cwd parameter, to run scriptB in its directory: import os from subprocess import check_call check_call([scriptB], cwd=os.path.dirname(scriptB))

Categories : Python

What do I do to make a python script that can run from any directory: the script file doesn’t have to be in the same directory as the .csv files?
Assuming you mean to include a fixed CSV file with your code, store an absolute path based on the script path: HERE = os.path.dirname(os.path.abspath(__file__)) csv_filename = open(os.path.join(HERE, 'somefile.csv') __file__ is the filename of the current module or script, os.path.dirname(__file__) is the directory the module resides in. For scripts, __file__ can be a relative pathname, so we use os.path.abspath() to turn that into an absolute path. This means you can run your script from anywhere. If you meant to make your script work with arbitrary CSV input files, use command line options: import argparse if __name__ == '__main__': parser = argparse.ArgumentParser('CSV importer') parser.add_argument('csvfile', type=argparse.FileType('w'), default

Categories : Python

Executing bash script from php script
I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP. e.g. /var/www/scripts/testscript Make sure the user/group for your testscript is the same as your webfiles. For instance if your client.php is owned by apache:apache, change the bash script to the same user/group using chown. You can find out what your client.php and web files are owned by doing ls -al. Then run <?php $message=shell_exec("/var/www/scripts/testscript 2>&1"); print_r($message); ?> EDIT: If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do. Execute root commands via PHP

Categories : PHP

Is it possible to get the time of executing my script and then use it in my script?
The easy way: Declare a variable at the start time: $Now = get-date This is a PowerShell object, so you do not need to worry about formatting, or how it reads. Then, to see what is newer then when the variable was created: ls | Where-Object {$_.CreationTime -lt $Now} | select Name Of course, you can adjust what happens with the found items, but there are the basics of it.

Categories : Powershell

How to sort a csv file through python script?
If I'm not mistaken the "a" tag opens for writing in this line: with open("csv_file.csv", "a") as inputfile: This means you're opening for writing, not for reading. You should use either "r" or "+".

Categories : Python

How do I output a .pdb file using python script?
This example code appears to do what you want: Relevant part is: import sys from Bio.PDB import PDBIO from Bio.PDB.PDBParser import PDBParser PDB_input = sys.argv[1] parser = PDBParser() structure = parser.get_structure('self', PDB_input) # DELETED CODE THAN MANIPULATED PDB OBJECT w = PDBIO() w.set_structure(structure) w.save('corrected_from_CHARMM_to_PDB.pdb')

Categories : Python

how to pass variable from python to shell script when shell script is getting called inside python script
You can: Step through the list, and then call mail.sh once for each file. This is the most reliable way. Convert the items in the list to a space delimited string, and then pass it in to mail.sh (assuming mail.sh is setup correctly, it should accept multiple arguments). What you cannot do is pass ['a.txt','b.txt','c.txt'] wholesale to the script.

Categories : Python

On Mac, how to create a drag & drop app for a python script where the script name rather than Python shows in the MenuBar (etc.)?
I have an answer to my question, but I am hoping that someone can come up with something less complex. The solution I came up with was a Python script to create an AppleScript (ugh!), compile it into a bundle and then modify the bundle to change the allowed file extension(s), the icon and so on. I did not find a way to get drag-and-drop working when starting a wxpython script, without an AppleScript (or using py2app) and I could not get the AppleScript to work in a bundle I created, I had to use osacompile to create the bundle for me. I like better the approach here or here, where one creates the plist file "by hand" rather than than modify an externally created one as I do here, but the script below does do the job. #!/usr/bin/env python '''This script creates an AppleScript app to

Categories : Python

zsh: how to autocomplete file names after python script name?
Honestly, IMO something in your shell configuration is breaking things up. Try doing this to verify it: zsh -f # starts a new shell ignoring your configuration autoload compinit compinit ./my-shell-script [TAB] it completes with files. That is the default. FWIW, if you want to bind a particular completer to a command/alias etc, you can do compdef _jstack jstack # simple _files completion compdef _files my-local-python-script # restrict to some file extensions compdef '_files -g "*.(eps|ps|pdf)"' okular

Categories : Osx

Perl script cannot call another perl script when executing inside C# application
What I ended up doing is that I passed the path of the folder where the required file was to the main.pl file as an input argument. In the main.pl file, I added the following line $lib_path = File::Spec->catfile($ARGV[3]); push @INC, $lib_path; which solved the issue.

Categories : C#

How to get a file on a memory stick read into a python script?
Since you don't explicitly open the file yourself, the simplest thing to do in this case would be to just make sure that the path to the file you pass asciitable.read() is valid. Here's what I mean: import asciitable import os from string import ascii_uppercase import sys PATH_TEMPLATE = '{}:/ECBGF/bg0809_protected.txt' for drive in ascii_uppercase[:-24:-1]: # letters 'Z' down to 'D' file_path = PATH_TEMPLATE.format(drive) if os.path.exists(file_path): break else: print 'error, file not found' sys.exit(1) x = asciitable.read(file_path, guess=False, delimiter=' ', fill_values=[('', '-999')])

Categories : Python

Trying to store raw bytes inside my one Python script file
You should encode the binary - for example, using base64 encloding - to turn the bytes into "legitimate characters". Then, when you need the binary information, you convert it back. See for example this earlier question for some code examples. A brief sample to get you going: # assume your bytes came from a file: bytesIneed = bytearray([234,232,231,188,122,132,145]) import base64 bytesConverted = base64.b64encode(bytesIneed) print "encoded string: " print bytesConverted bytesRecovered = base64.b64decode(bytesConverted) print "decoded binary: " for c in bytesRecovered: print(ord(c)) This will return the following output: encoded string: 6ujnvHqEkQ== decoded binary: 234 232 231 188 122 132 145 As you can see - the string 6ujnvHqEkQ== can be stored anywhere; and the decoding funct

Categories : Python

How I do get a python script that I run on a .cvs file locally, to work on MS SQL table?
You'll definitely need to rewrite the code and use python MSSQL driver: pyodbc or pymssql. Also, take a look at sqlalchemy sql toolkit and object relational mapper. It can help you to build an abstraction layer so that it would be easier for you to switch between different database backends in the future. Hope that helps.

Categories : Python

Import variable from Python script to Batch file
In Python Create a temp batch file in %TEMP%setvars.bat containing SET commands to set environment vars. You could use subprocess.POpen to run an ECHO something > path batch command so that %TEMP% can be used. In Batch Call the temp batch file : the vars are now available to use.

Categories : Python



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