Can I access sys.argv in python in interactive mode?
Asked Answered
C

4

7

I'd like to do something like:

% python foo bar
import sys
sys.argv

to get:

%  ['foo', 'bar']

but of course python dies when you enter an argument which is not a script or goes into non interactive mode if you do.

Can I do this somehow?

Causative answered 26/2, 2014 at 20:28 Comment(0)
A
15

Use - as script name:

python - foo bar

Test:

>>> import sys
>>> sys.argv
['-', 'foo', 'bar']
Arlenearles answered 26/2, 2014 at 20:34 Comment(0)
H
7
$ python - asdf asdf
Python 2.7.6 (default, Feb 15 2014, 23:06:13) 
[GCC 4.8.2 20140206 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv
['-', 'asdf', 'asdf']
>>> 
Huntlee answered 26/2, 2014 at 20:34 Comment(1)
+1 thanks for answering - ndpu got in 20s earlier... !Causative
B
2

Run python this way:

python - foo bar

Then

import sys
sys.argv

will work :)

Bedlam answered 26/2, 2014 at 20:35 Comment(0)
P
0

You could just set it manually for testing in IDLE:

try:
    __file__
except:
    sys.argv = [sys.argv[0], 'foo', 'bar']
Painful answered 26/2, 2014 at 20:32 Comment(2)
i thought about that, but i'm really an occasional python programmer and i'd like to verify i'm using the array properly. i usually just write the print statement and run a script, but it would be nice to do this on the command line...Causative
but running python foo bar won't run pythonBedlam

© 2022 - 2024 — McMap. All rights reserved.