In general, I can call python like this:
python ABC.py "{'a':1}"
then, in python I use ast.literal_eval to get dict.
how can I do this in powershell?
I have escape with ",but I can't get in the python.
start-process powershell -ArgumentList "-command python ABC.py '{`"a`":1}'"
not sure why I am unable to replicate, maybe its python issue but the following code is in my trash.py file
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a','--asd',help='asd',required=True)
args = vars(parser.parse_args())
print(type(eval(args['asd'])))
and when i run this from my power shell with the following command
python trash.py --a "{'a':1}"
it gave me the expected output :
<class 'dict'>
I am using python 3.6.8
Related
I am building a python file and instead of asking for user input I want it to get the information on the execution command. For example, I want to be able to type in
python code.py -i "information"
Instead of having to execute code.py and then tell the code "information". How do I do this? P.S. I am using MacOS mojave as the tags indicate. Thanks.
You can utilize sys.argv in your Python script to read command-line arguments and store them in a list of strings that you can then parse, as follows:
from __future__ import print_function
import sys
print(sys.argv)
Then, from the terminal:
> python code.py -i "foo bar"
['code.py', '-i', 'foo bar']
You can use python's argparse module to use command line arguments.
https://docs.python.org/3/library/argparse.html
When I manually run this command in Terminal, it executes, but through Python it gives the error that the directory is not available in Python packages.
I am using the following command
source ~/trytry/shell.sh
This is my test shell file:
#!/bin/sh
echo hello
when I executed " source ~/test.sh ", it will print hello at console.
This is my python code:
>>> import commands
>>> commands.getstatusoutput("source ~/test.sh")
(0, 'hello')
It works without any problem. So, would you please show your code?
What it looks like to me is that you have a shell script, and not a python file which would have the .py extension instead of .sh. The error may have to do with the fact that it isn't a python file you're trying to run.
Consider that you are in the Windows command prompt or similar command line environment. How can you get info about a Python module from its docstring printed to the console?
Ideally you will want to load the module without executing it, which could have side effects. This is supported by Python’s ast module, which even has a helper for getting docstrings. Try this:
python3 -c"import ast, sys; a = ast.parse(open(sys.argv[1]).read()); print(ast.get_docstring(a))" "$1"
The Shortut (Hack)
Generally (in 2.7):
python -c"print 'Hello world'"
(in 3.x):
python -c"print('Hello world')"
will output: Hello world
But if you pass -c as an argument into a module, something else happens.
For an example, navigate to [your Python folder]\Tools\Scripts. If your script does not take parameter -c, a shortcut is simply to run:
python reindent.py -c
This will result in an error for the argument: "-c not recognized", but it will also return the docstring to the console. (One limitation is that the output cannot be routed to the clipboard using |clip.)
Generally, if your script myscript.py contains a docstring and expects no argument -c:
python myscript.py -c
returns
option -c not recognized
[__docstring__]
The Works
Once you are in the folder of reindent.py you can get an error-free docstring:
python -c"import reindent; print reindent.__doc__"
For producing a browsable help text, which prints both the docstring and lists the containing classes, functions, and global variables, use:
python -c"import reindent; help(reindent)"
To output to the clipboard only (Warning: Contents will be replaced!):
python -c"import reindent; help(reindent)"|clip
Deeper
Now that you have figured out what classes and functions are accessible (see above), you can retrieve the methods of a class and inner docstrings:
python -c"from reindent import Reindenter; help(Reindenter)"
If you mean print interactively, just start python without any arguments to get a REPL (read–eval–print loop).
python
import mypackage
help(mypackage)
dir(mypackage)
executed one after another and so forth.
If you mean programmatically, see #noumenal's answer.
I would like to create a file that will be used as standard input for a python script, and invoke said script with subprocess.call.
When I do it directly in the command line it works fine:
The input file:
# test_input
1/2/3
The python script
# script.py
thisDate = input('Please enter date: ').rstrip()
The following command works just fine:
python script.py < test_input
But when I try to do the following from within another python script, it doesn't work. (from this)
outfile1 = open('test_input', 'w')
outfile1.write('1/2/3')
outfile1.close()
input1 = open('test_input')
subprocess.call(['python', 'script.py'], stdin=input1)
But then I get the following error:
>>>thisDate = input('Please enter date: ').rstrip()
>>>AttributeError: 'int' object has no attribute 'rstrip'
When I did some debugging, it seems that it is getting the integer 0 as the input.
What is causing the inconsistency here? Are the two methods not equivalent (evidently they are not, but why)? My ultimate goal is to perform the exact same task as the above command line version that worked.
Thank you
You are using input when it should be raw_input, input in python2 will eval the string. If you run the script with python3 it will work as is, for python2 change to raw_input.
Using check_call is usually a better approach and using with to open your files.
import subprocess
with open('test_input') as input1:
subprocess.check_call(['python3', 'script.py'], stdin=input1)
So chepner was correct. When I amended the following line:
subprocess.call(['python', 'script.py'], stdin=input1)
to:
subprocess.call(['python3', 'script.py'], stdin=input1)
it worked just fine.
(I am trying to do this in python3)
In the first instance, the file has two lines, and input() reads and parses the first line, which is a comment.
In the second case, the comment line is missing, so Python reads and parses a number.
You probably meant to use raw_input(), or run the script with Python 3.
(You probably also meant for the input file to end with a newline, and it doesn't really make sense to use subprocess.call() to run Python when you are already running Python.)
python script.py < test_input command should fail. You might mean: python3 script.py < test_input instead due to the difference between input() vs raw_input() on Python 2 as mentioned in other answers. python as a rule refers to Python 2 version.
if the parent script is run only using python3 then you could use sys.executable to run the child script using the same python version (the same executable):
#!/usr/bin/env python3
import subprocess
import sys
with open('test_input', 'rb', 0) as input_file:
subprocess.check_call([sys.executable or 'python3', 'script.py'],
stdin=input_file)
If the parent and the child may use different python versions then set the correct shebang in script.py e.g., #!/usr/bin/env python3 and run the script directly:
#!/usr/bin/env python
import subprocess
with open('test_input', 'rb', 0) as input_file:
subprocess.check_call(['./script.py'], stdin=input_file)
Here, the child script may choose its own python version. Make sure the script has executable permissions: chmod +x script.py. Note: Python Launcher for Windows understands the shebang syntax too.
Unrelated: use .communicate() instead of outfile1.write('1/2/3'):
#!/usr/bin/env python3
from subprocess import Popen, PIPE
with Popen(['./script.py'], stdin=PIPE, universal_newlines=True) as p:
p.communicate('1/2/3')
I am attempting to start the python interpreter by typing python into my terminal. I also want to pass some command line arguments. If I try python arg1 it things I am trying to open and run a script called arg1. So my question is, how can I pass command line arguments to python in the command line interpreter mode?
You already are.
Your arg1 is a command line argument - to the python interpreter.
Maybe you're thinking of a command line option? (which really is just a specific type of command line argument)
Using the -h argument (python -h) will print all such options.
python -Q new, for example, will launch the interpreter with the new float division by default.
On the other hand, if you want to pass command line arguments to your script, you need to specify them after the script name: python my_script.py arg1
If you are on a UNIX based system, you can also use a shebang on your script, which will allow you to simply execute your script by name, skipping python:
#!/usr/bin/env python
#your script here
then run ./my_script.py arg1
An easy way to do it is by using the subprocess module and input variables.
An example would be:
from subprocess import call
x = raw_input('Which command line arguments? ')
call(x, shell=True)
Try it with an ls command (dir for Windows users), it should work.
You can access the command line arguments using sys.argv
import sys
print sys.argv
% python scrpt.py a b c d
outputs: ['scrpt.py', 'a', 'b', 'c', 'd']
Use - to mark the end of python's interpreter options:
python --interpreter-option-1 --interpreter-option-2 - --my-custom-option option-value my-custom-argument