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

python - Using argparse, pass an arbitrary string as an argument to be used in the script
To get exactly what you're looking for, the trick is to use parse_known_args() instead of parse_args(): #!/bin/env python import argparse parser = argparse.ArgumentParser() parser.add_argument('-a', action="store_true") parser.add_argument('-b', action="store_true") opts = parser.parse_known_args() # Print info about flags if opts[0].a: print('You set the option "-a"') if opts[0].b: print('You set the option "-b"') # Collect remainder (opts[1] is a list (possibly empty) of all remaining args) if opts[1]: print('You passed the strings %s' % opts[1]) EDIT: The above code displays the following help information: ./clargs.py -h usage: clargs_old.py [-h] [-a] [-b] optional arguments: -h, --help show this help message and exit -a -b If you want to inform the user about the

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

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

Jenkins runs imported python script before main python script
The child process flushes its output buffers on exit but the prints from the parent are still in the parent's buffer. The solution is to flush the parent buffers before running the child: print("Starting script...") sys.stdout.flush() build.run()

Categories : Python

how to call a python script inside another python script where both in the same directory?
In script1.py place this: def main(): do something if __name__ == "__main__": main() In script2.py: import script1 if condition: script1.main()

Categories : Python

How to pass arguments from one python script on the server to another?
Use subprocess module: import subprocess args = [subject, body] subprocess.call(['python','SendMail.py'] + args) Inside SendMail.py use sys.argv: import sys subject, body = sys.argv[1:]

Categories : Python

How to: Pass Arguments to Python Script via Powershell
Got it! Darn single quotes..... $env:Path += ";c:Program Fileslcpython15"; $env:PATHEXT += ";.py"; $arg1 = "Test3" $arg2 = "Testing" $arg3 = 'c:ProgramDataset_cust_attr.py' python $arg3 $arg1 $arg2

Categories : Python

print result to cell SPSS python script
Not sure exactly how the SPSS interface works but I suspect it's not working because nearly every line in your code is invalid Python syntax. Try converting to the the following: import spss, spssaux spssaux.OpenDataFile('C:UsersšoťaDesktopdatacssd.sav') dlist = ['PARLAMENTCSSD2010'] ilist = ['KRAJCSSD2012'] vlist = ['VYSLEDKY'] ddim = len(dlist) idim = len(ilist) for i in range(ddim): if dlist[x] < ilist[x]: print ('the ilist is higher in cases: + .') spss.Submit("vlist[1]=vlist[1]+1")

Categories : Python

python send commands to interpreter from script and get result
Well, you can invoke python in the same way as you do a shell script and pass python code to it using the -c option. See http://docs.python.org/2/using/cmdline.html However, this is unbelievably insecure and I would not recommend doing it in a web app! If you are set on this, read up on restricted execution in Python http://docs.python.org/2/library/restricted.html

Categories : Python

how to pass an argument to a python script when starting with nohup
In general, the argument vector for any program starts with the program itself, and then all of its arguments and options. Depending on the language, the program may be sys.argv[0], argv[0], $0, or something else, but it's basically always argument #0. Each program whose job is to run another program—like nohup, and like the Python interpreter itself—generally drops itself and all of its own options, and gives the target program the rest of the command line. So, nohup takes a COMMAND and zero or more ARGS. Inside that COMMAND, argv[0] will be COMMAND itself (in this case, '/usr/bin/python'), and argv[1] and later will be the additional arguments ('/home/path/to/script/script.py' and whatever $BUCKET resolves to). Next, Python takes zero or more options, a script, and zero or more ar

Categories : Python

How to show result of python script in a console when running from ST editor?
SublimeREPL for is a plugin for SublimeText It does not open a cmd instance but can provide you a REPL, where You can provide input, which you usually cannot give on default console. Installation Install Package Control. http://wbond.net/sublime_packages/package_control Install SublimeREPL Preferences | Package Control | Package Control: Install Package Choose SublimeREPL Restart SublimeText2 Configure SublimeREPL (default settings in Preferences | Package Settings | SublimeREPL | Settings - Default should be modified in Preferences | Package Settings |SublimeREPL | Settings - User, this way they will survive package upgrades! Note from the documentation: ctrl+, , f means: press Ctrl and Comma, release all, press F. The keybinding above is used to Evaluate in REPL If Sublim

Categories : Python

How to pass dictionary as command line argument to python script?
Check this: >>> from sys import argv >>> from re import findall >>> args = ' '.join(argv[1:]) >>> pattern = r'([^=]+)s*=s*[s*([^]]+)s*]' >>> d = dict((t[0].strip(), map(lambda x: x.strip(', '),t[1].split())) for t in findall(pattern,args)) >>> for k,v in d.items(): try: d[k] = map(int,v) except: pass >>> d {'names': ['"J.J."', '"April"'], 'years': [25, 29]}

Categories : Python

How do I pass a c# variable to a python script from windows form application
You need to use a start info as seen here. http://www.dotnetperls.com/process-start ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "C:\Python27\Scripts\path\file.py"; startInfo.Arguments = "myvariable"; try { using (Process exeProcess = Process.Start(startInfo)) { //dostuff exeProcess.WaitForExit(); } } catch { //log throw; } The process returned by process.start is unmanaged and should be referenced inside a using.

Categories : C#

sys module giving different output when running Python script through IDLE and by double-clicking the script
print os.path.dirname(sys.executable) is what you should use. When you click it it is probably running through python.exe so you are removing the extra char from the w.

Categories : Python

Calling c++ function, from Python script, on a Mac OSX
How to compile my project so it can be used from python? I've read that I should create a *.so file but how to do so? That depends on your compiler. By example with g++: g++ -shared -o myLib.so myObject.o Should it work like a lib, so python calls some specific functions, chosen in python level? Yes it is, in my opinion. It seems do be the "obvious" way, since it's great for the modularity and the evolution of the C++ code.

Categories : C++

dump files from bash script in different directory from where python script ran it
You should change directory within the same command: cmd = "/path/to/executable/executable" outputdir = "/path/to/output/" subprocess.call("cd {} && {}".format(outputdir, cmd), shell=True)

Categories : Python

Cron not running Python script is script not in home folder
cron is running crontab(5) entries from the home directory of the user. You need to change appropriately the directory i.e. to call the chdir(2) syscall (either thru the cd shell builtin, or inside your python script using os.chdir). You should query the current directory (using getcwd(3), or the pwd command, or the os.getcwd in Python) in your script. Also check your PATH if running commands.

Categories : Python

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

How do scan a script for return values from a upper script in python?
Don't invoke a Python script from a Python script by using system, which spawns a whole other interpreter. Just import it. Like this: import ToBuildOrNot needsBuild = ToBuildOrNot.run() # or whatever you call your top-level function Since ToBuildOrNot.py is a script now, make sure the "main" function is protected so it doesn't execute automatically on import. Most people do it this way in Python: What does <if __name__=="__main__":> do?

Categories : Python

How do I access the URL's Query String in a Python CGI script?
First of all, the 'self' keyword is only available once defined in a function, typically an object's. It is normally used the same way 'this' is used in other OOP languages. Now, the snippet of code you were trying to use was intended for the Google App Engine, which you have not imported (nor installed, I presume). Since you are accustomed to using environment variables, here's what you can do: #!/usr/bin/python import os print os.environ.get("QUERY_STRING", "No Query String in url") However, I would advise you to use the cgi module instead. Read more about it here: http://docs.python.org/2/library/cgi.html

Categories : Python

Using a Selenium function in an Python / SST automation script
To access the underlying webdriver, you want to reference: sst.actions._test.browser Here is an example of an SST script that uses the webdriver.Firefox instance directly: import sst.actions # a regular SST action sst.actions.go_to('http:/testutils.org/sst') # now using webdriver directly sst.actions._test.browser.get('http://www.python.org') The example in your question could be written as: from sst.actions import * from selenium.webdriver.common import action_chains go_to('http:/yadayada.net/') ## perform a bunch of actions text = ## get text element with SST driver = sst.actions._test.browser action = action_chains.ActionChains(driver) action.double_click(text) action.perform()

Categories : Python

error with global name when running a script from another script - python
This is a pretty interesting problem. First a quick workaround, you can provide dictionaries to use as the local and global namespace when calling execfile(), using an empty dictionary for globals works fine: # test_fun1.py a = 1 def test1(): print a execfile('test_fun2.py', {}) test1() Alternatively, if you want the code to execute within the global scope of your module you can use globals() instead of {}. Now on to why this isn't working... from the documentation on execfile(): If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. Here "both dictionaries" is referring to the optional globals and locals arguments to execfile(). In this case "the environment where execfile() is called" is the local scope of the fun

Categories : Python

How run a Python script from another script and get resulting global dict?
Importing a module executes the code at the top level, and that module's "global" namespace gets imported as the name of the module james@bodacious:~$cat test.py def func(): pass myname = "michael caine" print "hello, %s" % myname james@bodacious:~$python Python 2.7.5 (default, Jul 12 2013, 18:42:21) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import test hello, michael caine >>> dir(test) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'func', 'myname'] >>> if the code you want to be run is at the top level of the file, just importing the module will execute the code and give you access to its "global" namespace all in one convenient package.

Categories : Python

ImportError when calling python script via a shell script
I had a similar problem. It turned out that in my bash script I was running the Python script with a different version of Python than I was on the command line (my env was set up with virtualenv on Python 2.7 but I was calling the script with Python3 from the bash script). There is nothing in your snippets indicating this is the case but it is worth checking to make sure that the Python versions match up.

Categories : Python

Python Script returns unintended "None" after execution of a function
In python the default return value of a function is None. >>> def func():pass >>> print func() #print or print() prints the return Value None >>> func() #remove print and the returned value is not printed. >>> So, just use: letter_grade(score) #remove the print Another alternative is to replace all prints with return: def letter_grade(score): if 90 <= score <= 100: return "A" elif 80 <= score <= 89: return "B" elif 70 <= score <= 79: return "C" elif 60 <= score <= 69: return "D" elif score < 60: return "F" else: #This is returned if all other conditions aren't satisfied return "Invalid Marks" Now use print(): >>> p

Categories : Python

When running Python's pdb as a script, how do I autostart the script?
that's probably not the way to do to it. you should modify/extend the existing pdb.py. the code looks like this: while True: try: pdb._runscript(mainpyfile) if pdb._user_requested_quit: break print "The program finished and will be restarted" except: traceback.print_exc() print "Uncaught exception. Entering post mortem debugging" print "Running 'cont' or 'step' will restart the program" t = sys.exc_info()[2] pdb.interaction(None, t) print "Post mortem debugger finished. The "+mainpyfile+" will be restarted" it looks like you could replace `pdb._runscript(mainpyfile)' with something like runpy.run_module(sys.argv[0], run_name="__main__", alter_sys=True) (from PEP 338). not a complete solutio

Categories : Python

How to get a python script to listen for inputs from another script
I would use a socket connection. Essentially you are writing a very simple server that only takes one connection at a time import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("localhost", 9988)) s.listen(1) while True: conn, addr = s.accept() data = conn.recv(1024) conn.close() my_function_that_handles_data(data) s.accept() is a blocking call. It waits for a connection. Then you do a read on the connection. In this case we are assuming the length of the parameters are only 1024 bytes. Then we do something with the data we received from the socket and wait for another connection. The client could look like this: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", 9988)) s.sendall('My parameters that I wan

Categories : Python

How to return a value from a shell script in a python script
use Subprocess.check_output instead of Subprocess.call. Subprocess.call returns return code of that script. Subprocess.check_output returns byte stream of script output. Subprocess.check_output on python 3.3 doc site

Categories : Python

Conversion of shell script to python script
It looks like you're after a templating engine, but if you wanted a straight forward, no thrills, built into the standard library, here's an example using string.Template: from string import Template with open('a.html') as fin: template = Template(fin.read()) print template.substitute(name='Bob') # <head>Bob</head> I thoroughly recommend you read the docs especially regarding escaping identifier names and using safe_substitute and such...

Categories : Python

Call a python script in a python script
Escape backslash () "C:\temp\hello2.py" or use raw string r"C: emphello2.py" >>> print "C: emphello2.py" C: emphello2.py >>> print "C:\temp\hello2.py" C: emphello2.py >>> print r"C: emphello2.py" C: emphello2.py

Categories : Python

How can I call a python script from a python script
1: why I don't see any prints out from 'b.py' and when I do 'ps -efW' I don't see a process named 'b.py'? Change run_b lines: p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr) You will not see a process named "b.py" but something like "python b.py" which is little different. You should use pid instead of name to find it (in your code "p.pid" has the pid). 2: Why when I kill a process like above, I see 'permission declined'? os.kill is supported under Windows only 2.7+ and acts a little bit different than posix version. However you can use "p.pid". Best way to kill a process in a cross platform way is: if platform.system() == "Windows" : subprocess.Popen("taskkill /F /T /PID %i" % p.pid , shell=True) else : os.killpg( p.

Categories : Python

python doesn't run script with 'python