I'm a newbie using python and ubuntu, and I'm trying to import sys to my code , but it always gave me an error with the element that is using sys:
import sys
Q = sys.argv[1]
the error came with every statement that is using the sys, even when I comment the one that has the error, the one after it then will have an error ...
Q = sys.argv[1]
the error:
"IndexError: list index out of range"
Q: Is there anyway to import sys to the pycharm ??
Q: What are the prerequisite of it?
This has nothing to do with the import. sys.argv[1] is the first argument provided to the Python script.
So if you do (for example)
C:\Python27> python.exe myscript.py Hello!
then sys.argv is ["myscript.py", "Hello!"], so sys.argv[1] is "Hello!".
If you don't provide an argument, then sys.argv will just be ["myscript.py"] - consequently, you can't access sys.argv[1] because it doesn't exist.
You have imported sys correctly. The error occurs when tying to access sys.argv[1], which is an argument you pass to the python executable.
If you just run python scriptname.py, without any other arguments, there is no sys.argv[1].
One way is to run your code in the terminal (Mac, Linux, or Unix) or the command prompt (Windows) as mentioned in the answer above by Tim, but for Linux/Unix/Mac you take out the .exe from python as follows: python myscript.py Hello
If you still want to do something similar in PyCharm, you have to pass the arguments as follows:
From the menu bar on the top, click on Run
Then click on Edit Configurations..
A dialog box will open, and then enter your arguments inside the Script Parameters field
Click Ok or Apply
Then run, or debug your code and it will run!
Related
My environment uses Python 2.6 and I'm new to Python. I need to write a script that runs a file decoding command which takes several arguments from the command line. My problem is I can't parse arguments taken from the terminal to the file decoding command.
For example if my program name is x.py and when i run "x.py Desktop/abc.txt" how can i pass Desktop/abc.txt as an argument to the cat command?
import commands
import sys
a=open("b.txt","w")
a.write(commands.getoutput('cat sys.argv[1]'))
When i researched it seemed that the above program should work but it didn't. Please help.
You should change commands.getoutput('cat sys.argv[1]') as commands.getoutput('cat %s' % (sys.argv[1],))
You're mixing up the terminal commands and Python commands. If you have a file called abc.py with the following code:
import sys
print sys.argv[1]
And you run it with python abc.py arg1, it should print out arg1.
For a cleaner and easier to read way of using command-line arguments if you want to control things like make sure they are int or allow multiple or whatever, I've had a lot of success using the argparse module in Python - it's much easier to use than the sys.argv style of parsing command-line arguments. Check out the official tutorial / docs here: https://docs.python.org/2/howto/argparse.html
I am attempting to use the os module in Python to clear the screen. As I'm using Fedora, the standard console command to clear the display is clear. When I type the following into a .py file:
from os import system
system("clear")
print("Hello world")
and run the file by opening a standard Terminal window and calling the file directly using the python shell command, it all works fine. However, if I type the same code into Ninja-IDE and execute it in the embedded console there, what comes out is the message "TERM environment variable not set" wherever I wanted to clear the screen.
Now, I'm aware that I can set the TERM environment variable if it is non-existant using something like this:
import os
try:
print(os.environ['TERM'])
except KeyError:
os.environ['TERM'] = foo
but, I'm unsure exactly what to set it to so that it works in Ninja-IDE. I've tried some of the obvious - xterm, xterm-256color, konsole - but they do not work for Ninja-IDE. Which leads to my question: what is the appropriate value of the TERM environment variable corresponding to the embedded console in Ninja-IDE? Or, alternatively, is it possible to tell Ninja-IDE to invoke an external terminal (such as xterm) when executing code, rather than using its own inbuilt console?
The answer is simple. It is caused by os.system. Simply add import system to your code and it is done, like this:
import os
import system
import shutil
import datetime
os.system('clear')
I am using the new Enthought Canopy code editor on OSX (64-bit). To test a script, I need to provide a command-line argument like:
import sys
config_file = sys.argv[1]
However, I can't seem to find a way to provide a command line argument to the script. I tried using a macro as:
def run():
code_task = get_active_task()
code_task.run_current_file('config_filename')
...but I get an error that run_current_file only takes one argument (presumably self).
Passing command line argument is not supported currently, but something that we plan to add.
As a work around, you could run the script normally, first, when it would fail, and then get the previous command from IPython history, and manually add in the args required.
Alternatively, you can set sys.argv to the args that you want to pass to your script, before running it. This seems sort of hackish to me.
In Windows XP when you open cmd.exe you get a console window with a command prompt looking like:
"C:\User and Settings\Staffer\My Documents>" where s> the underscore after the '>' is the cursor.
This is the default for Windows XP. A user might change it using the PROMPT=something or by using set PROMPT=something
In the console window, at the command prompt, entering the internal command "prompt" with no arguments does not return what the current prompt string is.
Is there a command or preferably a Python library that can retrieve what the command prompt is. I didn't want to write a Python module if there was a builtin way of retrieving that string.
The use case for getting the command prompt string is when I use the Python subprocess module to run a python program, and then return to the same console's command prompt while the subprocess is running, I get the cursor on a blank line. I can press Enter and the command prompt will redisplay; but it looks as if hasn't returned from the subprocess yet, which misleads my users.
One solution for the gui part of my app is to run pythonw runapp.py. However I'm left wondering if there's a way to get a clean command prompt when calling subprocess by using already made DOS commands, Python library, proper use of subprocess.Popen() and communicate()?
Not sure if it helps but if you enter "SET" from the command prompt you'll see a list of environment variables, including the current PROMPT (however it won't appear in the list if it's the default prompt).
From the command line:
c:\>echo %prompt%
$P$G
From Python:
>>> import os
>>> os.environ["PROMPT"]
'$P$G'
(http://docs.python.org/library/os.html#process-parameters)
[edit]
Ah, I missed your edit. It sounds like all you want to do is run the script in the background. I believe you are looking for the Windows "start" command with the /b option - http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/start.mspx?mfr=true
I think you are looking for this:
import os
print os.getcwd()
I'm trying to write a Python script to convert a bunch of images.
It's something like the following code (after a huge minimization):
#!/usr/bin/python
# -*- coding: utf-8 -*-
from subprocess import call
cmd = ' '.join(['convert.exe', '-resize', '110', 'foo\\a.jpg', 'bar\\a.jpg'])
print cmd
call(cmd)
I get the error below after executing it:
Parameter not valid - 110
While when I copy / paste the string emitted from the script on the command line the image convertion works perfectly.
What did I miss?
I would say that the error is most likely the result of two things
In the call command, try using shell=True as the second argument.
You're using relative paths, and the working directory might not be the same for python as it is from your cmd shell.
Are you sure the convert.exe your script is calling is the same one you are calling from the command line. I have, out of bitter experience, always used the full path to the executable I want to call from a script, Python or otherwise.
Windows XP has a command shell command named convert. When I feed it your command, I get the same error message you're seeing. I suspect it is being called instead of your convert.exe.